首先需要到MYSQL官方网站下载JDBC驱动,名称是:,然后将里面的jar包放到jre的lib/ext文件夹里,最后在Eclipse里导入到项目中:选中项目--右键Build Path--Configure Build Path--选择Libraries--Add External JARs,最后确定,这样就可以看到导入的JDBC连接MYSQL数据库的驱动了。
1 package day01; 2 3 import java.sql.DriverManager; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 7 import com.mysql.jdbc.Connection; 8 import com.mysql.jdbc.Statement; 9 10 public class Demo {11 public static void main(String[] args){12 //用Class.forName加载类Driver13 try {14 Class.forName("com.mysql.jdbc.Driver");15 } catch (ClassNotFoundException e) {16 e.printStackTrace();17 System.out.println("连接异常"+e);18 }19 /*数据库连接的三个参数:20 * url:数据库路径,格式:jdbc:mysql://ip地址/数据库名21 * user:数据库用户名22 * password:数据库密码23 * */24 25 String url = "jdbc:mysql://localhost/test";26 String user = "root";27 String password = "";28 29 try {30 //用DriverManager连接数据库,返回的类型要强制转换成Connection类型31 Connection conn = (Connection) DriverManager.getConnection(url, user, password);32 //创建陈述式,返回类型要强制转换成Statement类型33 Statement stmt = (Statement) conn.createStatement();34 //sql语句35 String sql = "select * from member where id = 3";36 //执行sql语句,获得结果集rs37 ResultSet rs = stmt.executeQuery(sql);38 //ResultSet对象的netx()方法将游标从结果集的第一行前移动到第二行前39 while(rs.next()){40 //rs.getString("name")或者该字段的值41 System.out.println(rs.getString("name"));42 }43 //关闭数据库连接44 rs.close();45 //关闭陈述式46 stmt.close();47 //关闭结果集48 conn.close();49 } catch (SQLException e) {50 e.printStackTrace();51 }52 53 }54 55 }