DBUtil
1.先创建两个JAVA class文件, 命名为DBUtil和test3
写DBUtil
package com.gongmao;
import java.sql.*;
public class DBUtil {
public static Connection getConnection() throws ClassNotFoundException,SQLException{
Class.forName(“com.mysql.jdbc.Driver”);
Connection connection = DriverManager.getConnection(“jdbc:mysql://127.0.0.1:3306/zjgm?characterEncoding=utf-8&user=root&password=123456&useSSL=false”);
return connection;
}
public static void closeAll(ResultSet resultSet, Statement statement,Connection connection) throws SQLException{
if(resultSet!=null){
resultSet.close();
}
statement.close();
connection.close();
}
}
2.写好DBUtil后在昨天原有代码基础上替换,替换后的代码为
package com.gongmao;
import java.sql.*;
public class test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
DBUtil dbUtil=new DBUtil();
Connection connection=dbUtil.getConnection();
System.out.println(“创建连接成功”);
//1.加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
//2.创建连接
//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.关闭资源
resultSet.close();
statement.close();
connection.close();
}
}
3.替换后的运行结果为以下截图,即为成功