JDBC获取数据库连接并处理结果集
import java.sql.*;
import java.util.ArrayList;
/**
* 获取jdbc连接
*/
public class GetCon {
/**
* 获取连接
*/
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//url
String url = "jdbc:mysql://localhost:3306/springboottest";
//用户名
String username = "root";
//密码
String password = "root";
//数据库对象
connection = DriverManager.getConnection(url, username, password);
String select = "select * from user";
//执行sql的对象
preparedStatement = connection.prepareStatement(select);
resultSet = preparedStatement.executeQuery();
ArrayList<String> strings = new ArrayList<>();
while (resultSet.next()){
String id = resultSet.getString("id");
strings.add(id);
}
System.out.println(strings.size());
System.out.println(strings.get(0));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
//关闭资源 固定写法 close resultSet,preparedStatement,connection
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}