如何使用Java更新MySQL数据库中的数据?
要向MySQL数据库表中更新数据,请使用UPDATE命令。语法如下 −
update yourTableName set yourColumnName1 = value1,....N where condition;
Mysql
首先,我们需要创建一个表。查询如下 −
mysql> create table UpdateDemo
-> (
-> id int,
-> Name varchar(200)
-> );
Query OK, 0 rows affected (0.67 sec)
Mysql
让我们向表中插入记录。查询如下 −
mysql> insert into UpdateDemo values(101,'John');
Query OK, 1 row affected (0.19 sec)
mysql> truncate table UpdateDemo;
Query OK, 0 rows affected (0.86 sec)
mysql> insert into UpdateDemo values(1,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UpdateDemo values(2,'Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into UpdateDemo values(3,'Smith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into UpdateDemo values(4,'David');
Query OK, 1 row affected (0.15 sec)
Mysql
现在,使用SELECT语句从表中显示所有记录。查询如下 −
mysql> select *from UpdateDemo;
Mysql
输出如下 −
+------+-------+
| id | Name |
+------+-------+
| 1 | John |
| 2 | Carol |
| 3 | Smith |
| 4 | David |
+------+-------+
4 rows in set (0.00 sec)
Mysql
这里是用Java更新MySQL数据库中记录的代码。我们将建立一个Java连接到MySQL数据库 −
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaUpdateDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e);
}
conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/business", "Manish", "123456");
System.out.println("Connection is created successfully:");
stmt = (Statement) conn.createStatement();
String query1 = "update UpdateDemo set Name='Johnson' " + "where id in(1,4)";
stmt.executeUpdate(query1);
System.out.println("Record has been updated in the table successfully..................");
} catch (SQLException excep) {
excep.printStackTrace();
} catch (Exception excep) {
excep.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Please check it in the MySQL Table. Record is now updated.......");
}
}
Mysql
输出如下 −
我们已经更新了id为1和4的数据。名称列已更新为“Johnson”。以下是使用SELECT语句检查表中数据是否已更新的查询。
mysql> select *from UpdateDemo;
Mysql
输出如下 −
+------+---------+
| id | Name |
+------+---------+
| 1 | Johnson |
| 2 | Carol |
| 3 | Smith |
| 4 | Johnson |
+------+---------+
4 rows in set (0.00 sec)
Mysql
从上面的输出可以看出,id为1和4的数据已经更新。
阅读更多:MySQL 教程