在jdbc代码中,加载驱动、创建链接、关闭资源的代码都是固定的,可以将这些代码放在一个类里面,这样就可以不用重复写这些代码,节省时间和精力。
新建一个DBUtill类把那几个固定的代码放入该类
package com.lzfthh;
import java.sql.*;
public class Dbutill {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/zjgm?user=root&password=123456&characterEncoding=utf-8&useSSL=true");
return connection;
}
public static void closeAll(ResultSet resultset,Statement statement,Connection connection) throws SQLException {
if(resultset!=null){
resultset.close();
}
statement.close();
connection.close();
}
}
主程序代码
package com.lzfthh;
import java.sql.*;
public class test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1 加载驱动
Connection connection = Dbutill.getConnection();
//2 创建链接
System.out.println("创建连接成功");
//3 写sql
String sql ="select * from stu";
//4 得到statement对象
PreparedStatement statement = connection.prepareStatement(sql);
//5 执行sql
ResultSet resultSet =statement.executeQuery();
//6 处理结果集
while (resultSet.next()){
int id =resultSet.getInt(1);
String name =resultSet.getString(2);
int age = resultSet.getInt(3);
System.out.println(id+name+age);
}
//7关闭资源
Dbutill.closeAll(resultSet,statement,connection);
}
}