【发布时间】:2018-11-12 20:59:12
【问题描述】:
我尝试使用 java 代码将数据插入 mysql 数据库。我在数据库中建立了一个用户表。用户表有 4 个字段:id、用户名、密码和地址。
mysql> desc user;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(32) | YES | | NULL | |
| password | varchar(64) | YES | | NULL | |
| address | varchar(64) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+
这是我的 java 代码。
Connection conn = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC";
String mysqlUserName = "root";
String mysqlPassword = "123456";
conn = DriverManager.getConnection(url, mysqlUserName, mysqlPassword);
String sql = "INSERT INTO user(username,password,address) VALUES (?,?,?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1,"11dsa1");
stmt.setString(2,"111");
stmt.setString(3,"111");
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (conn!=null)
conn.close();
}catch (SQLException e){
}
try {
if (stmt!=null)
stmt.close();
}catch (SQLException e){
}
}
未发生错误。 但是我的数据库中没有数据。
mysql> select * from user;
Empty set (0.01 sec)
但是我可以通过 shell 插入数据。
mysql> insert into user(username,password,address) values ("aaa","aaa","aaa");
Query OK, 1 row affected (0.09 sec)
mysql> select * from user;
+----+----------+----------+---------+
| id | username | password | address |
+----+----------+----------+---------+
| 22 | aaa | aaa | aaa |
+----+----------+----------+---------+
1 row in set (0.00 sec)
但是id是22而不是1!
其实我之前已经运行了这个java代码21次。我的理解是这段java代码可以将数据插入mysql,但会立即从数据库中删除数据。 我真的无法理解这种荒谬的情况
【问题讨论】:
-
不处理就不要捕获异常
-
你永远不会执行准备好的语句
-
使用 try-with-resources 而不是在 finally 中关闭 Statement 和 Connection
-
如果在 finally 中关闭语句,则不能在 try 块中关闭它
-
@Jens 感谢您的评论。我会遵守这些规则。