这里写自定义目录标题
用户类UserInfo,主要用于生成用户的一些信息,获取用户的信息。
用户有三个属性 id,username,password.
private int id;
private String username;
private String password;
生成他构造函数
public UserInfo(String username, String password) {
this.username = username;
this.password = password;
}
生成Get,Set函数用右键点击空白处![这次点击最下方的Generate]
(https://img-blog.csdnimg.cn/20190627231205768.png)
函数![按住Ctrl键点击上面的属性,依次生成各个属性的get,set的函数]
(https://img-blog.csdnimg.cn/20190627231606719.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hhbnRpYW5fNw==,size_16,color_FFFFFF,t_70)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
上面就是生成id的get,set函数,怎么样效果不错吧。
接下来是一个toString()函数,可以在Generate 中用toString生成。
public String toString() {
return "UserInfo{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
然后就是建立一个UserInfoDao的类,先坐坐准备工作
ResultSet resultSet=null;
PreparedStatement statement=null;
Connection connection=null;
List<UserInfo> userInfos=new ArrayList<>();
接下来就是重头戏了
try{
connection = DBUtil.getConnection();
....
....
....
}
是不是发现了什么,对需要建立DBUtil类,在这里用到了他的getConnection()方法 try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection
("jdbc:mysql://127.0.0.1:3306/idea?useSSL=true&" +
"characterEncoding=utf-8&user=root&password=root");
return connection;
} catch (Exception e) {
e.printStackTrace();
}
然后一个语句 System.out.println("创建连接pan'd成功")就可以判断连接是否成功
String sql="select * from userinfo";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()){
int id=resultSet.getInt(1);
String username=resultSet.getString(2);
String passsword=resultSet.getString(3);
UserInfo userInfo=new UserInfo(username,passsword);
userInfo.setId(id);
userInfos.add(userInfo);
}
System.out.println(userInfos);
DBUtil.close(resultSet,statement,connection);
在close函数中要注意去判断 resuleSet,statement,connection的值是否为空。
public static void close(ResultSet resultSet, Statement statement,Connection connection){
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
在这里只写一个增加的代码,删除改变,查询都是相似的
public void addUser(UserInfo userInfo){
Connection connection=null;
PreparedStatement statement=null;
try {
connection=DBUtil.getConnection();
String sql="insert into userinfo (id,username,password) values (?,?,?)";
statement = connection.prepareStatement(sql);
statement.setInt(1,userInfo.getId());
statement.setString(2,userInfo.getUsername());
statement.setString(3,userInfo.getPassword());
statement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.close(null,statement,connection);
}
}