eclipse通过jdbc连接数据库8.0.15版本
eclipse通过jdbc连接数据库8.0.15版本
数据库8.0.15的jdbc的下载网址:https://dev.mysql.com/downloads/connector/j/
先选中箭头所指的选项,然后下载红线圈中的zip文件,然后解压。(记住jdbc文件的路径)
右击要连接数据库的项目名称,选中Build Path,然后点击Configure Build Path,如图
点击add external JARS,选中解压文件中的mysql-connector-java-8.0.15,如图
String driver = "com.mysql.cj.jdbc.Driver";
// 获取mysql连接地址
String url = "jdbc:mysql://localhost:3306/zxq?&useSSL=false&serverTimezone=UTC";
// 数据名称
String username = "root";
// 数据库密码
String password = "123456";
// 获取一个数据的连接
Connection conn = null;
try{
Class.forName(driver);
//getConnection()方法,连接MySQL数据库!
conn=DriverManager.getConnection(url,username,password);
if(!conn.isClosed())
System.out.println("数据库连接成功!");
//创建statement类对象,用来执行SQL语句!
Statement Statement=conn.createStatement();
//要执行的SQL语句
String sql="select * from students" ;
//ResultSet类,用来存放获取的结果集!
ResultSet rs=Statement.executeQuery(sql);
System.out.println("-------------------------------");
System.out.println("执行结果如下所示:");
System.out.println("-------------------------------");
System.out.println("姓名" + "\t" + "性别"+"\t");
System.out.println("-------------------------------");
String id=null;
String name=null;
String math=null;
String chinese=null;
while(rs.next()){
//获取‘学号’这列数据
id=rs.getString("name");
//获取‘姓名’这列数据
name=rs.getString("sex");
//获取‘数学成绩’这列数据
System.out.println(id+"\t"+name);
}
rs.close();
conn.close();
}
catch(ClassNotFoundException e){
//数据库驱动类异常处理
System.out.println("数据库驱动加载失败!");
e.printStackTrace();
}
catch(SQLException e1){
//数据库连接失败异常处理
e1.printStackTrace();
}
catch(Exception e2){
e2.printStackTrace();
}
finally{
System.out.println("-------------------------------");
System.out.println("数据库数据获取成功!");
}
程序运行截图: