1、首先新建一个javaweb项目(正在学习中,对于这方面不太了解)
dao层的连接数据库的代码(仅仅是其中一个方法,简单的获取列表)
public List<User> getAll(){
List<User> users = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
String driverClass = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/javaweb?characterEncoding=utf-8&serverTimezone=UTC";
String userName ="root";
String password = "123456";
Class.forName(driverClass);
connection = DriverManager.getConnection(url, userName, password);
String sql = "SELECT id, user_name username, password, mobile, update_time updateTime "
+ "FROM user";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
String id = resultSet.getString(1);
String username = resultSet.getString(2);
String passwords = resultSet.getString(3);
String mobile = resultSet.getString(4);
String updateTime = resultSet.getString(5);
User user = new User(id,username,passwords,mobile,updateTime);
users.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return users;
}