7

到目前为止,只有当我在 executeUpdate 语句中声明值时,我才能将数据插入到我的 SQL 表中。我想知道是否有一种方法可以将这些值作为变量传递,我将在执行方法中声明为参数,如下所示:

public void updateSQL(String name, String dnsName, String ipV4, String ipV6, int statusCode)
{
    try
    {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");

        System.out.println("Database Name: " + connection.getMetaData().getDatabaseProductName());

        Statement statement = connection.createStatement();

        statement.executeUpdate("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID)" + "VALUES(@Name, @DNSName, @IPAddressV4, @IPAddressV6, @StatusCodeID)");
        System.out.println("Data Inserted");

        ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");

        while(resultSet.next())
        {
            System.out.println("Computer Name: " + resultSet.getString("Name"));
        }

        connection.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        System.err.println("Problem Connecting!");
    }
}

我已经尝试了几种不同的方法,但到目前为止还没有运气。有人知道这是否可以做到吗?

4

2 回答 2

13

您可以使用PreparedStatement代替Statement.

PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();

使用这种方式,您可以防止 SQL 注入。

于 2012-08-22T17:56:08.540 回答
3

看看这里:

PreparedStatement prep = conn.prepareStatement("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID) VALUES(?, ?, ?, ?, ?)");
prep.setString(1, name);
prep.setString(2, dnsName);
prep.setString(3, ipV4name);
prep.setString(4, ipV6);
prep.setInt(5, statusCode);
prep.executeUpdate();

将帮助您理解。

于 2012-08-22T18:02:07.390 回答