0

这是我的代码:

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){        
    }       
  }  
}

如果只有一列,这很好用。我将如何指定列?

4

2 回答 2

3

如果只有一列,这很好用。我将如何指定列?

只需在查询的列列表中指定列名。

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

顺便说一句,我建议您在使用 JDBC 执行 SQL 查询时使用PreparedStatement而不是Statement使用,以防止 SQL 注入。

于 2013-01-25T00:47:29.303 回答
0

这是一个演示。

        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
    }
    }
}
于 2013-01-25T01:47:27.457 回答