0

我一直在尝试将值保存到一个名为“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:

在过去的两天里,我一直在这样做,但没有任何成功。我会非常非常非常感激任何愿意来拯救我的人。谢谢你。

4

5 回答 5

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字符串应该是这样的:

"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();
于 2013-08-22T04:54:10.183 回答
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();
于 2013-08-22T04:44:50.887 回答
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.
于 2013-08-22T04:47:48.540 回答
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";
于 2013-08-22T04:50:43.897 回答
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();
    }
于 2013-08-22T07:04:25.803 回答