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

Ari*_*jas 0 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();
            }   

        }
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 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) {}
}
Run Code Online (Sandbox Code Playgroud)

如果提供的优势是可以消除任何潜在的SQL注入 攻击,与使用其他答案建议的字符串连接相反.

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

也可以看看: