使用Java将变量值插入SQL Server [英] Inserting variable values into SQL Server using Java

查看:93
本文介绍了使用Java将变量值插入SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. What I wanted to know if there is a way that I can pass those values as variables that I will declare as parameters in the executing method like so:

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!");
    }
}

我尝试了几件不同的东西但没有运气至今。任何人都知道这是否可以做到?

I've tried couple of different things but no luck so far. Anyone know if this can be done?

推荐答案

您可以使用 PreparedStatement 代替 Statement

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

使用这种方法可以防止SQL注入。

Using this way, you prevent SQL injection.

这篇关于使用Java将变量值插入SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆