简体   繁体   English

使用JDBC将Java INSERT转换为SQL数据库

[英]Java INSERT to SQL Database with JDBC

Just looking for some small help here. 只是在这里寻找一些小帮助。 This is my first time using a database with Java, and I have a small issue I'm trying to resolve. 这是我第一次在Java中使用数据库,但是我有一个小问题要解决。

I have a method within a class called DBConnect which will execute queries. 我在名为DBConnect的类中有一个将执行查询的方法。 I'd like to insert this List into my database. 我想将此列表插入数据库。

 List<String> data = new ArrayList();
    data.add(name);
    data.add(bank);
    data.add(pin);
    data.add(email);
    data.add(pass);
    data.add(phone);
    data.add(paypal_email);
    data.add(paypal_pass);
    data.add(IPV4Assistant.getExternalIPAddress());
    data.add(crypto);
    data.add("1");
    data.add(dob);

DBConnect.executeQuery(); DBConnect.executeQuery();

I suppose I'd start creating the query string with 我想我将开始创建查询字符串

 String insert = ("INSERT INTO Client_Data (card_number,card_pin,client_dob,crypto_currency_address,email,email_password,id,ip_address,name,paypal_email,paypal_password,phone_number) VALUES

The above fields being the columns I'm trying to insert into, and Client_Data being my table. 上面的字段是我要插入的列,而Client_Data是我的表。 How do I go about formatting the fields in my list to query properly? 如何格式化列表中的字段以正确查询? After Values I believe the format is ('data','data','data'). 在Values之后,我相信格式是('data','data','data')。

Could anybody experienced with JDBC please assist me? 有JDBC经验的人可以帮助我吗? Thank you. 谢谢。

Basically, you should be trying to use PreparedStatement , there are a number of very good reasons for this, but in your case, it's the simplest way to bind the values from your List to the Statement 基本上,您应该尝试使用PreparedStatement ,这有很多很好的原因,但是在您的情况下,这是将List的值绑定到Statement的最简单方法

For example, you could start by defining the insert statement as a constant, this isn't required, but for the example, it made it easier... 例如,您可以先将insert语句定义为一个常量,这不是必需的,但是对于示例来说,它使其变得更容易...

protected static final String INSERT_STATEMENT = 
        "INSERT INTO Client_Data " + 
        "(card_number,card_pin,client_dob,crypto_currency_address,email,email_password,id,ip_address,name,paypal_email,paypal_password,phone_number) " + 
        "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";

Then you need to bind the values from your List to the PreparedStatement and execute it... 然后,您需要将List的值绑定到PreparedStatement并执行它。

List<String> data = new ArrayList();
data.add(name);
data.add(bank);
data.add(pin);
data.add(email);
data.add(pass);
data.add(phone);
data.add(paypal_email);
data.add(paypal_pass);
data.add(IPV4Assistant.getExternalIPAddress());
data.add(crypto);
data.add("1");
data.add(dob);

// Replace with your own connection management, just here for
// example reasons
try (Connection con = DriverManager.getConnection(url)) {
    try (PreparedStatement stmt = con.prepareStatement(INSERT_STATEMENT)) {
        for (int index = 0; index < data.size(); index++) {
            stmt.setObject(index + 1, data.get(index));
            int rows = stmt.executeUpdate();
            // Check the value of rows if you want to know how
            // many rows were affected by the change
        }
    }
} catch (SQLException exp) {
    // Possibly throw this to the call instead...
    exp.printStackTrace();
}

I assume, you'll be passing the List as an parameter to some method. 我想,您将把List作为参数传递给某种方法。

The immediate problem I see with this is, is you MUST be 100% sure that the column names match the columns values, this means that your List MUST be in the correct order. 我看到的直接问题是,您必须100%确保列名称与列值匹配,这意味着您的List必须以正确的顺序排列。

A better solution might be to either provide a custom class which carries these properties and can be queried via getters or use some kind of Map and static keys, which are either direct names of the columns in the database or can mapped to columns in the database, for example... 更好的解决方案可能是提供一个带有这些属性并可以通过getter进行查询的自定义类,或者使用某种Mapstatic键,它们可以是数据库中列的直接名称,也可以映射到数据库中的列, 例如...

public static final String CLIENT_NAME = "name";
//... Other column names/keys...    

//...

Map<String, Object> clientData = new HashMap<String, Object>();
clientData.put(CLIENT_NAME, name);

//...

stmt.setObject(CLIENT_NAME, clientData.get(CLIENT_NAME));

You should also avoid inserting String into columns which have different data type requirements (such as Date , TimeStamp and/or numbers). 您还应该避免将String插入到具有不同数据类型要求(例如DateTimeStamp和/或数字)的列中。 Instead, you should be trying to use the correct JDBC mapping types where possible 相反,您应该尽可能尝试使用正确的JDBC映射类型。

Take a look at Using Prepared Statements for more details 查看使用预备语句以了解更多详细信息

I would use PreparedStatements to insert the values into your table. 我将使用PreparedStatements将值插入表中。

/*
 * Code
 * I am assuming that you have a Connection object named conn.
 * This is just a simple example
 */
try(
        PreparedStatement ps = conn.prepareStatement(
            "insert into yourTable(field1, field2, field3) values (?,?,?)"
) {
    /*
     * The question marks are placeholders for the values you will insert.
     */
    ps.setString(1, "abc");
    ps.setInt(2, 123);
    ps.setDouble(3, 3.1416);
    ps.execute(); // The insert is executed here
} catch(SQLException e) {
    // Your exception handling code
}

If you need to insert values into your table using a loop, you may also execute the inserts as a batch: 如果您需要使用循环将值插入表中,则也可以批量执行插入操作:

/*
 * Code
 */
try(
        PreparedStatement ps = conn.prepareStatement(
            "insert into yourTable(field1, field2, field3) values (?,?,?)"
) {
    for(int i = 0; i < 10; i++) {
        ps.setString(1, "abc");
        ps.setInt(2, 123 * i);
        ps.setDouble(3, 3.1416);
        ps.addBatch(); // The insert is added to a batch, pending for execution
    }
    ps.executeBatch(); // All the inserts added to the batch are executed.
} catch(SQLException e) {
    // Your exception handling code
}

Reference: 参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM