MySQL 如何使用Java删除数据库中的数据
使用DELETE命令从MySQL数据库中删除数据。其语法如下所示。
delete from yourTableName where condition;
Mysql
我将使用JAVA编程语言从MySQL数据库中删除数据。首先,创建一个表并插入一些记录。以下是创建表的查询。
mysql> create table DeleteTableDemo
-> (
-> id int,
-> Name varchar(200)
-> );
Query OK, 0 rows affected (0.94 sec)
Mysql
在上述表中插入记录。将记录插入表的查询如下所示。
mysql> insert into DeleteTableDemo values(101,'Smith');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DeleteTableDemo values(102,'Johnson');
Query OK, 1 row affected (0.27 sec)
Mysql
现在我们可以检查我的表中有多少条记录。该查询如下所示。
mysql> select *from DeleteTableDemo;
Mysql
结果如下。
+------+---------+
| id | Name |
+------+---------+
| 101 | Smith |
| 102 | Johnson |
+------+---------+
2 rows in set (0.00 sec)
Mysql
我们的表中有两条记录。现在,让我们使用delete命令删除MySQL数据库表中的数据。以下是通过JAVA代码删除id=101数据的代码。在此之前,我们将建立到MySQL数据库的Java连接。
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 JavaDeleteDemo {
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 = "delete from DeleteTableDemo " +
"where id=101";
stmt.executeUpdate(query1);
System.out.println("Record is deleted from 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 deleted.......");
}
}
Mysql
输出如下。
mysql> select *from DeleteTableDemo;
Mysql
输出如下。
+------+---------+
| id | Name |
+------+---------+
| 102 |Johnson |
+------+---------+
1 row in set (0.00 sec) 我们已删除id为101的数据。
Mysql
阅读更多:MySQL 教程