将数据插入数据库 - org.h2.jdbc.JdbcSQLException:列数不匹配; SQL语句:

时间:2013-08-22 04:35:57

标签: java database h2

我一直在尝试将值保存到名为“CLIENT”的数据库中。

通过以下代码创建数据库:

package Database;

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExampleCreateTables {
    // JDBC driver name and database URL
    private static String JDBC_DRIVER = "org.h2.Driver";
    private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";

    //  Database credentials
    private static String USER = "sa";
    private static String PASS = "";

    public static void main (String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            //STEP 4: Execute a query
            System.out.println("Creating table in given database...");
            stmt = conn.createStatement();

            String sql = "CREATE TABLE CLIENT " +
                    "(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " + 
                    " fullNames VARCHAR(255), " + 
                    " iDNumber VARCHAR(255), " + 
                    " pINNumber VARCHAR(255), " + 
                    " passportNumber VARCHAR(255), " + 
                    " postOfficeBoxNumber VARCHAR(255), " + 
                    " postalCode VARCHAR(255), " + 
                    " telephoneNumberLandline VARCHAR(255), " + 
                    " telephoneNumberMobile VARCHAR(255), " + 
                    " CARD VARCHAR(255)) "; 

            stmt.executeUpdate(sql);
            System.out.println("Created table in given database...");

        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt!=null)
                    conn.close();
            } catch(SQLException se) {
            } // do nothing
            try {
                if (conn!=null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } // end finally try
        } // end try
        System.out.println("Goodbye!");
    } // end main
} // end

我尝试保存到数据库中的类是:

package Database;

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExampleInsertRecords {
    public final String values;
    public final String table;

    public JDBCExampleInsertRecords (String values, String table) 
    {
        this.values = values;
        this.table = table;
    }

    // JDBC driver name and database URL
    private static String JDBC_DRIVER = "org.h2.Driver";
    private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";

    //  Database credentials
    private static String USER = "sa";
    private static String PASS = "";

    public static void main () {
        Connection conn = null;
        Statement stmt = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName(getJDBC_DRIVER());

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
            System.out.println("Connected database successfully...");

            //STEP 4: Execute a query
            System.out.println("Inserting records into the table...");
            stmt = conn.createStatement();

            String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
            stmt.executeUpdate(sql);

            System.out.println("Inserted records into the table...");

        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            //finally block used to close resources
            try {
                if (stmt != null)
                    conn.close();
            } catch (SQLException se) {
            } // do nothing
            try {
                if (conn!=null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } //end finally try
        } //end try

        System.out.println("Goodbye!");
    } //end main

    /**
     * @return the JDBC_DRIVER
     */
    public static String getJDBC_DRIVER() {
        return JDBC_DRIVER;
    }

    /**
     * @param aJDBC_DRIVER the JDBC_DRIVER to set
     */
    public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
        JDBC_DRIVER = aJDBC_DRIVER;
    }

    /**
     * @return the DB_URL
     */
    public static String getDB_URL() {
        return DB_URL;
    }

    /**
     * @param aDB_URL the DB_URL to set
     */
    public static void setDB_URL(String aDB_URL) {
        DB_URL = aDB_URL;
    }

    /**
     * @return the USER
     */
    public static String getUSER() {
        return USER;
    }

    /**
     * @param aUSER the USER to set
     */
    public static void setUSER(String aUSER) {
        USER = aUSER;
    }

    /**
     * @return the PASS
     */
    public static String getPASS() {
        return PASS;
    }

    /**
     * @param aPASS the PASS to set
     */
    public static void setPASS(String aPASS) {
        PASS = aPASS;
    }
} //end

获取值的代码位于名为“AddNewClient”的类中,如下所示:

    public String getValues () {
    String fullNames = fullNamesJTextField.getText();
    String iDNumber = identificationNumberJTextField.getText();
    String pINNumber = pINNumberJTextField.getText();
    String passportNumber = passportNumberJTextField.getText();
    String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
    String postalCode = postalCodeJTextField.getText();
    String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
    String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();

    List<String> client = new ArrayList<String>();

    client.add(fullNames);
    client.add(iDNumber);
    client.add(pINNumber);
    client.add(passportNumber);
    client.add(postOfficeBoxNumber);
    client.add(postalCode);
    client.add(telephoneNumberLandline);
    client.add(telephoneNumberMobile);

    StringBuilder builder = new StringBuilder();
    String listStringClient = "";

    for (String s : client)
    {
        listStringClient += "NULL" + "'" + s + "'" + ",";
    }

    return listStringClient;
}

我收到错误消息:

run:
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:

过去两天我一直在这里,但没有成功。对于那些愿意来救我的人,我会非常,非常非常感激。谢谢。

5 个答案:

答案 0 :(得分:2)

这是一个问题所在:

String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);

值应该是getValues()方法,而不仅仅是字符串,所以

String sql = "INSERT INTO CLIENT VALUES (" + getValues() + ")";

此外,由于您未指定哪些列,因此假定所有列都在值中输入。如果CARD在SQL数据库中没有默认值,并且它不能为NULL,那么您将遇到问题。

最后,这有点奇怪:

for (String s : client)
{
    listStringClient += "NULL" + "'" + s + "'" + ",";
}

你需要的是值,而不是'NULL',所以它应该是

for (String s : client)
{
    listStringClient += "'" + s + "'" + ",";
}

最后,你这样做的方式,你最后会有一个额外的逗号(例如:'value1','value2','value3')

剪切最后一个逗号:

return listStringClient.substring(0, listStringClient.size() - 1);

当然,有一种更好的方法可以在没有额外逗号的情况下进行for循环。

结束,sql String应如下所示:

"INSERT INTO CLIENT VALUES('value1','value2','value3','value4','value5','value6')"

执行System.out.println(sql)并查看您尝试执行的String语句。然后你会看到错误。

这是在没有逗号问题的情况下构建值字符串的更好方法:

Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();

while (iter.hasNext()) {
    sb.append("'").append(iter.next()).append("'");
    if (iter.hasNext())
        sb.append(",");
}
return sb.toString();

答案 1 :(得分:1)

您未在声明中传递任何值。以下代码是静态的,它没有参数:

INSERT INTO CLIENT " + "VALUES ((values))

这是无意义的SQL命令:INSERT INTO CLIENT VALUES((values))。你想快递

String sql = "INSERT INTO CLIENT VALUES " + getValues()";

我更喜欢使用PreparedStatement,因为它是安全的,它将逃脱危险的字符:

String sql = "INSERT INTO PRODUCT VALUES(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "asdf");
prest.setInt(2, 2009);
// etc
int count = prest.executeUpdate();

答案 2 :(得分:1)

您忘记提及CARD列的值。如果您不想在那里设置任何值,只需传递' '

您的for循环应该是这样的

for (String s : client)
{
    listStringClient += "NULL" + "'" + s + "'" + ",";//GIVES YOU ERROR BECAUSE AT THE END OF
}                                               // FOR LOOP IT HAS , IN THE END OF STRING.
 listStringClient+="' '";//This is for CARD COLUMN.

答案 3 :(得分:1)

我认为不是:

String sql = "INSERT INTO CLIENT " + "VALUES ((values))";

你想要这样的东西:

String sql = "INSERT INTO CLIENT " + "VALUES ("+getValues()+")";

getValues的实现也有点奇怪:

for (String s : client)
{
    listStringClient += "NULL" + "'" + s + "'" + ",";
}

可能是:

for (String s : client)
{
    listStringClient += "'" + s + "',"
}
listStringClient += "NULL";

答案 4 :(得分:0)

我不能完全感谢你的惊人答案。我提出了各种想法,并为我的问题提出了这个解决方案。

我上面的问题的工作答案来自Leos Literak,abmitchell,Vimal Bera和Grisha的答案。

通过以下代码创建数据库:

package Database;

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExampleCreateTables {
    // JDBC driver name and database URL
    private static String JDBC_DRIVER = "org.h2.Driver";
    private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";

    //  Database credentials
    private static String USER = "sa";
    private static String PASS = "";

    public static void main (String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            //STEP 4: Execute a query
            System.out.println("Creating table in given database...");
            stmt = conn.createStatement();

            String sql = "CREATE TABLE CLIENT " +
                    "(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " + 
                    " fullNames VARCHAR(255), " + 
                    " iDNumber VARCHAR(255), " + 
                    " pINNumber VARCHAR(255), " + 
                    " passportNumber VARCHAR(255), " + 
                    " postOfficeBoxNumber VARCHAR(255), " + 
                    " postalCode VARCHAR(255), " + 
                    " telephoneNumberLandline VARCHAR(255), " + 
                    " telephoneNumberMobile VARCHAR(255)) "; 

            stmt.executeUpdate(sql);
            System.out.println("Created table in given database...");

        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt!=null)
                    conn.close();
            } catch(SQLException se) {
            } // do nothing
            try {
                if (conn!=null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } // end finally try
        } // end try
        System.out.println("Goodbye!");
    } // end main
} // end

保存到数据库中的类是:

package Database;

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExampleInsertRecords {
    public static String values;
    public final String table;

    public JDBCExampleInsertRecords (String values, String table) 
    {
        this.values = values;
        this.table = table;
    }

    // JDBC driver name and database URL
    private static String JDBC_DRIVER = "org.h2.Driver";
    private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";

    //  Database credentials
    private static String USER = "sa";
    private static String PASS = "";

    public static void main () {
        Connection conn = null;
        Statement stmt = null;

        try {
            //STEP 2: Register JDBC driver
            Class.forName(getJDBC_DRIVER());

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
            System.out.println("Connected database successfully...");

            //STEP 4: Execute a query
            System.out.println("Inserting records into the table...");
            stmt = conn.createStatement();

            String sql = "INSERT INTO CLIENT VALUES (NULL, " + (values) + ")";

            stmt.executeUpdate(sql);

            System.out.println("Inserted records into the table...");

        } catch (SQLException se) {
            //Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            //Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            //finally block used to close resources
            try {
                if (stmt != null)
                    conn.close();
            } catch (SQLException se) {
            } // do nothing
            try {
                if (conn!=null)
                    conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            } //end finally try
        } //end try

        System.out.println("Goodbye!");
    } //end main

    /**
     * @return the JDBC_DRIVER
     */
    public static String getJDBC_DRIVER() {
        return JDBC_DRIVER;
    }

    /**
     * @param aJDBC_DRIVER the JDBC_DRIVER to set
     */
    public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
        JDBC_DRIVER = aJDBC_DRIVER;
    }

    /**
     * @return the DB_URL
     */
    public static String getDB_URL() {
        return DB_URL;
    }

    /**
     * @param aDB_URL the DB_URL to set
     */
    public static void setDB_URL(String aDB_URL) {
        DB_URL = aDB_URL;
    }

    /**
     * @return the USER
     */
    public static String getUSER() {
        return USER;
    }

    /**
     * @param aUSER the USER to set
     */
    public static void setUSER(String aUSER) {
        USER = aUSER;
    }

    /**
     * @return the PASS
     */
    public static String getPASS() {
        return PASS;
    }

    /**
     * @param aPASS the PASS to set
     */
    public static void setPASS(String aPASS) {
        PASS = aPASS;
    }
} //end

获取值的代码位于名为“AddNewClient”的类中,如下所示:

    public String getValues () {
    String fullNames = fullNamesJTextField.getText();
    String iDNumber = identificationNumberJTextField.getText();
    String pINNumber = pINNumberJTextField.getText();
    String passportNumber = passportNumberJTextField.getText();
    String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
    String postalCode = postalCodeJTextField.getText();
    String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
    String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();

    List<String> client = new ArrayList<String>();

    client.add(fullNames);
    client.add(iDNumber);
    client.add(pINNumber);
    client.add(passportNumber);
    client.add(postOfficeBoxNumber);
    client.add(postalCode);
    client.add(telephoneNumberLandline);
    client.add(telephoneNumberMobile);

    Iterator<String> iter = client.iterator();
    StringBuilder sb = new StringBuilder();

    while (iter.hasNext()) {
        sb.append("'").append(iter.next()).append("'");
        if (iter.hasNext())
            sb.append(",");
    }

    return sb.toString();
    }