Question

Here is my code:

import java.sql.*;

public class clazz{
  public static void main(String[] args) {

    try{
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database","root","password");
      Statement stmt = (Statement) con.createStatement();

      String insert = "INSERT INTO table VALUES ('value')";
      stmt.executeUpdate(insert);

    }catch(Exception e){        
    }       
  }  
}

This works great and all, if there's only one column. How would I specify the column?

No correct solution

OTHER TIPS

This works great and all, if there's only one column. How would I specify the column?

Just specify the column name in the column list in your query.

String insert = "INSERT INTO table (colname1, colname2) VALUES ('value1','value2')";

Btw, I would recommend you to use PreparedStatement instead of Statement while executing SQL queries using JDBC in order to prevent SQL Injection.

Here is a demo.

        create table t_customer (
  id number(19, 0) not null,
  first_name varchar2(50) not null,
  last_name varchar2(50) not null,
  last_login timestamp null,
  comments clob null,
  constraint pk_customer primary key(id)
)   

public class InsertDemo {
    private static final String CONNECTION_STRING =
        "jdbc:oracle:thin:@oracle.devcake.co.uk:1521:INTL";
    public static void main(String[] args) {
    try {
        Class.forName("oracle.jdbc.OracleDriver");
    } catch (ClassNotFoundException e) {
        return;
    }
    Connection connection;
    try {
        connection = DriverManager.getConnection(CONNECTION_STRING,
            "PROSPRING", "x******6");
    } catch (SQLException e) {
        return;
    }
    PreparedStatement preparedStatement;
    try {
        preparedStatement = connection.prepareStatement(
            "insert into t_customer (id, first_name, last_name, last_login, " +
                "comments) values (?, ?, ?, ?, ?)");
    } catch (SQLException e) {
        return;
    }
    try {
        preparedStatement.setLong(1, 1L);
        preparedStatement.setString(2, "Jan");
        preparedStatement.setString(3, "Machacek");
        preparedStatement.setNull(4, Types.TIMESTAMP);
        preparedStatement.setNull(5, Types.CLOB);
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        return; // 1
    }
    try {
        connection.commit();
    } catch (SQLException e) {
        return;
    }
    try {
        connection.close();
    } catch (SQLException e) {
        // noop
    }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top