package com.zhongruan;
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(“创建连接成功”);
//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.关闭资源
dbUtil.closeAll(resultSet,statement,connection);
}
}
package com.zhongruan;
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”);
return connection;
}
public static void closeAll(ResultSet resultSet,Statement statement,Connection connection) throws SQLException{
if (resultSet!=null){
resultSet.close();
}
statement.close();
connection.close();
}
}