[英]Inserting variable values into SQL Server using Java
So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. 到目前为止,只有当我在executionUpdate语句中声明值时,我才能将数据插入到我的SQL表中。 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? 任何人都知道这是否可以做到?
You may use PreparedStatement
instead of Statement
. 您可以使用PreparedStatement
而不是Statement
。
PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();
Using this way, you prevent SQL injection. 使用这种方式,可以防止SQL注入。
Have a look here : 看看这里:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.