0

How can I update my SQL Table column with the value that is stored in a local variable.

In my program I have taken value from the HTML page using the following statement:

String idd=request.getParameter("id");
String report=request.getParameter("rprt");

So now I have to update the value of report in my database table named "ptest" and I am using the following query:

Class.forName("com.mysql.jdbc.Driver"); 
java.sql.Connection con = 
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root"); 
Statement st= con.createStatement(); 
ResultSet rs; 
int i=st.executeUpdate("update ptest set result = @reprt where patient_id= 
@idd");


out.println("Successfully Entered");   

But the value is not being stored in the database instead NULL is being stored.

I have already seen this question and got no help. Question

Please ignore my mistakes if any in this question as I am new to MYSQL.

verygolo
  • 95
  • 1
  • 9
Piyush Agarwal
  • 102
  • 1
  • 14

2 Answers2

2

You can use prepared statements in java.

setString or setInt can set different data types into your prepared statements.

The parameter 1, 2 are basically the positions of the question mark. setString(1,report) means that it would set the string report in the 1st question mark in your query.

Hope this code helps you in achieving what you want.

String query = "update ptest set result = ? where patient_id = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);

preparedStatement.setString(1, report);
preparedStatement.setString(2, idd);

preparedStatement.executeUpdate();
Farhan Qasim
  • 990
  • 5
  • 18
0

In JDBC, you use ? as placeholders for where you want to inject values into a statement. So you should do something like this ...

Class.forName("com.mysql.jdbc.Driver"); 
java.sql.Connection con = 
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root"); 
PreparedStatement st= con.prepareCall("update ptest set result = ? where patient_id= 
?"); 

///now set the params in order
st.setString(1, report);
st.setString(2, idd);
//then execute
st.executeUpdate();

Doing a string concat with the values is dangerous due to sql injection possibilities, so I typically make statement text static and final, and also if your value has a ' in it that could blow up your sql syntax etc. Also, notice the use of executeUpdate rather than query. Hope this helps

Mark Giaconia
  • 3,844
  • 5
  • 20
  • 42