“eclipse连接mySql数据库”论文是黑龙江职业学院重点培育课题“移动实习就业跟踪系统”成果,课题编号为:YJP201309的科研成果.
网上有关于eclipse连接mySql数据库资料,在百度上搜索相关信息,完全符合标题的很多,但阐述的都不详细,现就eclipse连接mySql问题通过实例进行分析.
一、正确安装MySQL.
打开下载的mysql安装文件mysql-5.5.32-win32.zip正确安装,为了数据安全,不要把mysql安装在系统盘,如C:盘.如果是重新安装mysql的话,要注意先备份好mysql目录中的data目录,这个目录是所有用户的数据目录,非常重要.重装时,备份好数据后,先卸载掉旧的mysql,并删除原mysql安装目录.注意选择Custom选项,这样才能修改安装目录.
二、创建一个MySql数据库结果如图1所示.
三、打开Eclipse,创建一个项目(myTest),安装mysql直连驱动jar包.
步骤:右键点击myTest--->build Path--->add external Archiver...选择jdbc驱动,点击确定.
四、驱动已经导入,下面我们来写一个程序验证一下.在myTest工程下建Class文件,名为mySql_1,输入如下代码:
import ja.sql.*;
public class mySql_1
{
public static void main(String args[])
{ try
{
Class.forName(".mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
//Class.forName(".gjt.mm.mysql.Driver");
System.out.println("成功安装Mysql驱动!");
}
catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try
{
Connection connect 等于 DriverManager.getConnection("jdbc:mysql://localhost:3306/myTest","root","z");
System.out.println("成功 Mysql怎么写作!");
Statement stmt 等于 connect.createStatement();
ResultSet rs 等于 stmt.executeQuery("select * from test_1"); //z 为你表的名称
while (rs.next())
{
System.out.print(rs.getString("id")+" ");
System.out.print(rs.getString("name"));
System.out.println(rs.getString("age"));
} }
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
} } }
五、我们来写一个程序验证一下向MySQL数据库中插入数据.在myTest工程下建Class文件,名为mySql_2,输入如下代码,往MySQL的Test_1表中插入10条数据.
import ja.sql.*;
public class mySql_2
{
public static void main(String args[])
{ try
{
Class.forName(".mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
//Class.forName(".gjt.mm.mysql.Driver");
System.out.println("成功安装Mysql驱动!");
}
catch (Exception e)
{ System.out.print("错误安装Mysql驱动!");
e.printStackTrace();
} try
{ Connection connect 等于 DriverManager.getConnection( "jdbc:mysql://localhost:3306/mytest","root","z");
int num等于10;
PreparedStatement Statement等于connect.prepareStatement("insert into test_1 values(?,?,?)");
for(int i等于0;i Statement.setString(1,"No."+i);//给第一个问号赋值; Statement.setString(2,"姓名"+i); //给第二个问号赋值; Statement.setInt(3,100+i); //给第三个问号赋; Statement.executeUpdate(); } // } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // System.out.println("An error has occurred:"+e.toString()); // e.printStackTrace(); } catch(SQLException e) { } } } pstmtInsert.setString(1,"a");//给第一个问号赋值"a"; pstmtInsert.setString(2,"b");//给第二个问号赋值"b";