使用 Java 将记录插入 MySQL 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18270414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:55:04  来源:igfitidea点击:

Inserting records into a MySQL table using Java

javamysqlsqljdbcinsert-into

提问by

I created a database with one table in MySQL:

我在 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)
);

I tried to insert a record using Java:

我尝试使用 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!");
  }
}

The output appears to return successfully: insert_success

输出似乎成功返回: 插入成功

But when I select from MySQL, the inserted record is blank: mysql_blank_record

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

Why is it inserting a blank record?

为什么插入空白记录?

采纳答案by Stefan Beike

no that cannot work(not with real data):

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

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

change it to:

将其更改为:

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

Create a PreparedStatment with that sql and insert the values with index:

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

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

回答by Bilbo Baggins

this can also be done like this if you don't want to use prepared statements.

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

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

Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.

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

回答by Satyen Udeshi

There is a mistake in your insert statement chage it to below and try : String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

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

回答by sudarshan kakumanu

This should work for any table, instead of hard-coding the columns.

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

//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);

    }