使用JDBC将变量添加到数据库

时间:2012-02-04 23:34:25

标签: java sql jdbc

如何将记录添加到我的数据库中?我担心,当我这样做时,在数据库中会有包含“veriable1”但不包含veriable1内容的单元格。这是对的吗?

public class Record
{
    public Record(String veriable1, String veriable2) throws IOException, SQLException
        {
           addRecord();
        }

        private void addRecord() throws IOException, SQLException
        {   
            try
            {
                Statement stat = DataBase.Connect().createStatement();

                stat.executeUpdate("INSERT INTO tableName "
                                 + "(veriable1, veriable2) "
                                 + "VALUES "
                                 + "(veriable1, veriable2)");
            }
            finally
            {
                BazaDanych.Polacz().close();
            }   

        }

2 个答案:

答案 0 :(得分:6)

您可以(应该)使用PreparedStatement

String SQL = "INSERT INTO tableName (variable1, variable2) VALUES (?, ?)";
Connection connection = null;
PreparedStatement statement = null;

try {
    connection = database.getConnection();
    statement = connection.prepareStatement(SQL);
    statement.setString(1, variable1);
    statement.setString(2, variable2);
    statement.executeUpdate();
} finally {
    if (statement != null) try { statement.close(); } catch (IOException ignore) {}
    if (connection != null) try { connection.close(); } catch (IOException ignore) {}
}

如果提供的优势是可以消除任何潜在的SQL injection attacks,与使用其他答案所建议的字符串连接相反。

另请注意,我稍微重写了资源的处理方式。上面的方法是标准的JDBC习语。它确保在PreparedStatement关闭之前Connection也已关闭,否则当Connection涉及池化连接时,您将耗尽资源。

另见:

答案 1 :(得分:0)

您应该在SQL语句中添加变量本身,请参阅此

 stat.executeUpdate("INSERT INTO tableName "
                             + "(veriable1, veriable2) "
                             + "VALUES "
                             + "("+veriable1+", "+veriable2+")");
        }