0

I have a form and I want to send the data to a database. How can I pass the request data through the method parameters and send it to the Database?

int status = InsertCustomer(fName, mName, lName , iage, issn, city, state, country);

//Method // This method should return an int that the executeUpdate       // methods returns. Note: the driver name and the URL are       // already available in the init() method.

  private int InsertCustomer(String firstName, String midName, String lastName, int age, int ssn, String city, String state, String country) {

    // JDBC logic


    try {
        Class.forName(driverName);
        Connection conn = DriverManager.getConnection(databaseURL);
        java.sql.Statement st = conn.createStatement();


        st.executeUpdate("INSERT INTO Customer(firstName, midName, lastName, age, ssn, city, state, country)" + 
                   "VALUES ('?', '?', '?', ?, ?, '?', '?', '?')";


    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    return 1;
}

I'm a lil bit lost, a little would be very much appreciated.

1 Answer 1

2

Either you use a simple (i.e. not prepared statement), and you can't pass any parameter:

String sql = "insert into sometable (a, b, c) values (7, 8, 9)";
Statement st = conn.createStatement();
return st.executeUpdate(sql);

Or (and in your case, that's what you should do), you use a prepared statament and pass parameters:

String sql = "insert into sometable (a, b, c) values (?, ?, ?)";
PreparedStatement st = conn.prepareStatement(sql);
st.setInt(1, 7);
st.setInt(2, 8);
st.setInt(3, 9);
return st.executeUpdate();

In your code, you're using a simple statement and try to execute a SQL query which needs parameters. That's not possible. You need a prepared statement to do that.

More information in the JDBC tutorial.

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

4 Comments

Thank You, let me give it a try
Question: is the a, b, c database columns?
Just a note: please respect the Java naming conventions: methods start with a lower-case letter; variables are not prefixed with m, f, l, i or any other letter.
Yes, a, b and c are columns of the table sometable in the example.

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.