如何使用 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 数据库中插入了记录。

更新时间:2019-07-30

14K+ 浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.