eclipse中java链接mysql步骤

来源:互联网 发布:debian与centos 编辑:程序博客网 时间:2024/06/04 19:18

1.下载并安装mysql     

mysql官网下载链接

mysql5.6安装图解

SQLyog_Enterprise


2.下载mysql驱动程序

mysql-connector-java-5.1.39-bin.jar


3.在eclipse中导入数据库所需要用的jar包(也就是mysql驱动程序)


a.在工程下新建lib文件夹,然后把jar包复制进去



b.在jar包上右键,选择Build Path -> Configure Build Path



c.选择Libraries - > Add JARs-->然后到lib下找到对应的数据库驱动jar包



d.导入过后,出现Referenced Libraries,在里面可以看到导入的jar包了



4.具体代码实现:

package cn.edu.ahui;import java.sql.*;     public class TestJdbc {  public static void main(String[] args) {  ResultSet rs = null;  Statement stmt = null;   Connection conn = null;  try{  //第一步:注册数据库驱动 Class.forName("com.mysql.jdbc.Driver");     //第二步:连接数据库  ,(链接javaee数据库)conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaee", "root", "root");   //第三步:创建数据库语句对象  stmt = conn.createStatement();  //第四步:执行数据库语句 会返回ResultSet对象  ,查询leo表中的数据rs = stmt.executeQuery("select * from leo");  //第五步:遍历数据库  while(rs.next()) {  System.out.print(rs.getString(1) + "  ");System.out.print(rs.getString(2) + "  ");System.out.print(rs.getString(3) + "  ");System.out.println();}  }catch(ClassNotFoundException e){   e.printStackTrace();  }catch(SQLException e){  e.printStackTrace();  }finally{   try{  if(rs != null){  rs.close();  rs = null;   }   if(stmt != null){  stmt.close();  stmt = null;  }  if(conn != null){   conn.close();   conn = null;  }  }catch(SQLException e){  e.printStackTrace();  }   }   }  }  


说明,我的账户名和密码都是root,每个人可能不一样,然后创建了一个javaee数据库,数据库有leo这张表,表中有两行三列数据。运行结构如下:



1 0