SelectUser
package Java_EE.MySQL.day04.JDBC_Demo2_DQL;
import Java_EE.MySQL.util.JDBCUtils01;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DemoSelectUser {
public static void main(String[] args) {
List<User> users = JdbcSelect(); //调用查询数据表
for (User user : users) {
System.out.println(user);
}
}
//查询数据库db1中的数据表user的数据
public static List<User> JdbcSelect() {
ArrayList<User> users = new ArrayList<>();
Connection conn = null;
PreparedStatement pstat = null;
ResultSet rs = null;
try {
//第一步:注册驱动
// Class.forName("com.mysql.jdbc.Driver");
//第二步:获取数据库连接对象
// conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root");
conn= JDBCUtils01.getConnection();
conn.setAutoCommit(false);//开启事务
//第三,四步:定义SQL语句,获取执行SQL的对象
pstat = conn.prepareStatement("select * from USER");
//第五步:执行SQL
rs = pstat.executeQuery();
//第六步:处理结果
User user = null;//定义User对象,准备接收查询出来的数据
while(rs.next()){
//接收数据
int id = rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
//添加到集合
user = new User(id,name,password);
users.add(user);
}
conn.commit();//提交事务
} catch (Exception e) {
if(conn != null){
try {
conn.rollback();//只要有任何的异常发生,事务都会“回滚”
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
//第七步:关闭资源
}finally {
JDBCUtils01.close(rs,pstat,conn);
/*
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstat != null){
try {
pstat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
*/
}
return users;
}
}
|
|