【问题标题】:Inserting records into a MySQL table using Java使用 Java 将记录插入 MySQL 表
【发布时间】:2013-08-18 16:31:59
【问题描述】:

我在 MySQL 中创建了一个只有一张表的数据库:

CREATE DATABASE iac_enrollment_system;

USE iac_enrollment_system;

CREATE TABLE course(
    course_code CHAR(7),
    course_desc VARCHAR(255) NOT NULL,
    course_chair VARCHAR(255),
    PRIMARY KEY(course_code)
);

我尝试使用 Java 插入记录:

// STEP 1: Import required packages
import java.sql.*;
import java.util.*;

public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";

// Database credentials
static final String USER = "root";
static final String PASS = "1234";

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    Scanner scn = new Scanner(System.in);
    String course_code = null, course_desc = null, course_chair = null;

    try {
        // STEP 2: Register JDBC driver
        Class.forName("com.mysql.jdbc.Driver");

        // STEP 3: Open a connection
        System.out.print("\nConnecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        System.out.println(" SUCCESS!\n");

        // STEP 4: Ask for user input
        System.out.print("Enter course code: ");
        course_code = scn.nextLine();

        System.out.print("Enter course description: ");
        course_desc = scn.nextLine();

        System.out.print("Enter course chair: ");
        course_chair = scn.nextLine();

        // STEP 5: Excute query
        System.out.print("\nInserting records into table...");
        stmt = conn.createStatement();

        String sql = "INSERT INTO course " +
            "VALUES (course_code, course_desc, course_chair)";
        stmt.executeUpdate(sql);

        System.out.println(" SUCCESS!\n");

    } catch(SQLException se) {
        se.printStackTrace();
    } catch(Exception e) {
        e.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("Thank you for your patronage!");
  }
}

输出似乎成功返回:

但是当我从 MySQL 中选择时,插入的记录是空白的:

为什么要插入空白记录?

【问题讨论】:

  • 您没有在查询中使用 course_*** 变量。
  • 您没有在插入语句上设置任何值。检查使用带有绑定变量的preparedStatement,而不是组成一个“字符串”插入语句。这将插入数据并阻止您遇到 SQL 注入问题。

标签: java mysql sql jdbc insert-into


【解决方案1】:

不,不能工作(不使用真实数据):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

改成:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

使用该 sql 创建一个 PreparedStatment 并插入带有索引的值:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

【讨论】:

  • 您好,我尝试将部分代码更改为this。但它为变量prepareStatement 返回cannot find symbol
  • 当然你必须在使用前创建它。
  • PreparedStatement PreparedStatement = conn.prepareStatement(sql);
  • 嗨,对不起,如果我是新手。我已经更改了代码。 Here 是我的粘贴箱。它正在抛出Can not issue data manipulation statements with executeQuery()
【解决方案2】:

如果您不想使用准备好的语句,也可以这样做。

String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"

为什么它没有插入值是因为您没有提供值,而是提供了您使用过的变量的名称。

【讨论】:

  • 您应该始终使用preparedStatements。这种类型的代码是不好的做法,会导致 SQL 注入问题。
  • Aayush,我不同意。你不应该学习坏习惯,因为它们会坚持下去。从一开始就学会使用preparedStatements,你会写出更好的代码。
  • 我不是要求学习和使用它,我之所以提到它是因为它是一项功能,人们应该知道这一点,而且这也解决了他的答案。
  • 我个人不再用这个了,我用的是像hibernate这样的ORM框架。
  • 我选择使用 PreparedStatement 方法。不过,您对它为什么不插入值的解释很有帮助。为此点赞。谢谢。
【解决方案3】:

这应该适用于任何表格,而不是对列进行硬编码。

//Source details
    String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";
    String sourceUserName = "src";
    String sourcePassword = "***";

    // Destination details
    String destinationUserName = "dest";
    String destinationPassword = "***";
    String destinationUrl = "jdbc:mysql://server:3306/db";

    Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
    Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);

    PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT *  FROM src_table ");
    ResultSet rs = sourceStatement.executeQuery();
    rs.setFetchSize(1000); // not needed


    ResultSetMetaData meta = rs.getMetaData();



    List<String> columns = new ArrayList<>();
    for (int i = 1; i <= meta.getColumnCount(); i++)
        columns.add(meta.getColumnName(i));

    try (PreparedStatement destStatement = destConnection.prepareStatement(
            "INSERT INTO dest_table ("
                    + columns.stream().collect(Collectors.joining(", "))
                    + ") VALUES ("
                    + columns.stream().map(c -> "?").collect(Collectors.joining(", "))
                    + ")"
            )
    )
    {
        int count = 0;
        while (rs.next()) {
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                destStatement.setObject(i, rs.getObject(i));
            }
            
            destStatement.addBatch();
            count++;
        }
        destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
        System.out.println("done " + count);

    }

【讨论】:

    【解决方案4】:

    您的插入语句中有错误,请将其更改为以下内容并尝试: String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

    【讨论】:

    • 虽然这也解决了问题,但我选择使用 PreparedStatement 方法。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多