Samar Qureshi
Samar Qureshi

Reputation: 23

Prepared Statements from text fields in java

Sorry to sound stupid.. but i am wanting to create a prepared statement to get rid of the injection in my java project. The problem is that i don't seem to understand how to convert int into String from the text box data and use it in the statement. i have been researching for hours but got nothing! this is my Injected code:

 this.sql_Query = "update customer set cust_id ='" + 
     String.valueOf(txtcust_id.getText()) + ",'" + txtcust_name.getText() +
     "','" + txtf_name.getText() + "','" + txtb_date.getText() + "' , '" +
     txtcnic.getText() + "','" + txtcity.getText() + "','" +
     txtcard_num.getText() + "',,'" + txtacc_num.getText() + "',,'" +
     txtb_n.getText() + "',,'" + txtadd.getText() + "',,'" +
     txtemail.getText() + "','" + txtph_num.getText() + "' )";

and this is what i have converted this into:

String query = "INSERT INTO customers( cust_id , cust_name , father_name, birth_date, CNIC," 
            city, card_num, acc_num, bank_name, address , email, ph_num ) values (?,?,?,?,?,?,?,?,?,?,?,?);
            pst = conn.prepareStatement(query); // create a statement
            pst.setInt(1, cust_id); // set input parameter 1
            pst.setString(2, "cust_name"); // set input parameter 2
            pst.setString(3, "father_name"); // set input parameter 3
            pst.setDate(4, birth_date );
            pst.setBigint(5, CNIC);
            pst.setString(6, "city");
            pst.setBigint(7, card_num);
            pst.setBigint(8, acc_num);
            pst.setString(9, "bank_name");
            pst.setString(10, "address");
            pst.setString(11, "email");
            pst.setBigint(12, ph_num);
            pstmt.executeUpdate();

I can't understand how to deal with the integer type stuff in here. I would appreciate all the help i can get as this is making me so frustrated.

Upvotes: 0

Views: 2287

Answers (2)

Stephen Souness
Stephen Souness

Reputation: 272

Obtaining an int from a String should be simple enough.

Just wrap each String that is supposed to be an int with:

pst.setInt(x, Integer.parseInt(yourVarNameHere));

To make your code more robust you should probably do the conversion from String to int as a separate validation step which will catch NumberFormatException if the incoming String is not parseable.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

You could first validate the input entered if it passes criteria (number, valid range) then you could convert String to int by

Integer.parseInt(numberInString)

Upvotes: 1

Related Questions