Based on Monster group and GPT:
You can write the insert() method to insert data into the database as follows:
private void insert(){
String username = enrolView.getUsernametext().getText();
char[] chars = enrolView.getPasswordtext().getPassword();
String password = new String(chars);
Connection conn = null;
PreparedStatement ps = null;
try {
//获取数据库连接
conn = DBUtil.getConn();
//插入数据的SQL语句
String sql = "INSERT INTO users (`user_name`,`pwd`) values(?,?)";
//创建PreparedStatement对象,并设置参数
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
//执行插入操作
int rows = ps.executeUpdate();
//判断是否插入成功
if (rows > 0) {
JOptionPane.showMessageDialog(enrolView, "注册成功!");
} else {
JOptionPane.showMessageDialog(enrolView, "注册失败!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
DBUtil.closePs(ps);
DBUtil.closeConn(conn);
}
}
In the insert() method above, we first get the username and password and store them in the username and password variables. We then get the database connection object by calling the DBUtil.getConn() method and INSERT the user name and password into the users table by performing an insert statement using the PreparedStatement object.
Note that we use the PreparedStatement object here to execute the SQL statement. The advantage of this is that SQL injection attacks are effectively avoided.
finally, we close the resource in the finally block by calling the DBUtil.closePs(ps) and DBUtil.closeConn(conn) methods.