7

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?

2 Answers 2

14

You may use PreparedStatement instead of 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.

Sign up to request clarification or add additional context in comments.

1 Comment

it should be stmt.executeUpdate() here
3

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();

this will help you understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.