如何使用 Java 向 MySQL 資料庫插入資料?
要向 MySQL 資料庫插入資料,請使用 INSERT 命令。語法如下:
INSERT INTO yourTableName(yourColumnName1,........yourColumnNameN)values(Value1,Value2,......ValueN);
在此,我使用 JAVA 程式語言在 MySQL 資料庫中插入記錄。首先,我們需要在 MySQL 中建立一個表。查詢如下:
mysql> create table InsertDemo -> ( -> Id int, -> Name varchar(200), -> Age int -> ); Query OK, 0 rows affected (0.97 sec)
現在,以下是使用表 InsertDemo 向 MySQL 資料庫中插入記錄的 JAVA 程式碼。在此之前,我們將建立一個到 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 JavaInsertDemo {
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:///business", "Manish", "123456");
System.out.println("Connection is created successfully:");
stmt = (Statement) conn.createStatement();
String query1 = "INSERT INTO InsertDemo " + "VALUES (1, 'John', 34)";
stmt.executeUpdate(query1);
query1 = "INSERT INTO InsertDemo " + "VALUES (2, 'Carol', 42)";
stmt.executeUpdate(query1);
System.out.println("Record is inserted 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......... ……..");
}
}示例輸出如下:

要檢查記錄是否已插入表中,請使用 SELECT 語句。查詢如下:
mysql> select *from InsertDemo;
輸出如下:
+------+-------+------+ | Id | Name | Age | +------+-------+------+ | 1 | John | 34 | | 2 | Carol | 42 | +------+-------+------+ 2 rows in set (0.00 sec)
如上所示,我們已經成功在 MySQL 資料庫中插入了記錄。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP