连接数据库步骤的简单代码
/**
-
实体类
*/
public class User {//主键
private Integer userid;
//用户名
private String username;
//密码
private String password;public Integer getUserid() {
return userid;
}public void setUserid(Integer userid) {
this.userid = userid;
}public String getUsername() {
return username;
}public void setUsername(String username) {
this.username = username;
}public String getPassword() {
return password;
}public void setPassword(String password) {
this.password = password;
}@Override
public String toString() {
return “User{” +
“userid=” + userid +
“, username=” + username +
“, password=” + password +
‘}’;
}
}
/**
-
执行代码的先后顺序
*/
public class UserController {/**
-
查询
-
@return
*/
public List select() {Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;ArrayList users = new ArrayList();
//1.加载驱动
try {
Class.forName(“com.mysql.jdbc.Driver”);//2.建立连接 connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/newsdb_month", "root", "123"); //3.执行sql返回结果 String sql = "select * from user"; ps = connection.prepareStatement(sql); rs = ps.executeQuery(); //4.处理结果集 while (rs.next()) { User user = new User(); user.setUserid(rs.getInt("userid")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); users.add(user); } return users;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//5.释放资源
try {
connection.close();
ps.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
-
}