In our student table, we will add 10 marks to one student who’s id = 3. After updating the record we will display the id, name and mark of the student.
import java.sql.*;
public class my_connect {
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/my_tutorial","root","test");
Statement st=con.createStatement();
// Display record before the update , create restultSet
ResultSet rs=st.executeQuery("SELECT * FROM STUDENT WHERE id=3");
rs.next();
System.out.println(rs.getInt(1)+" "+rs.getString("name") + " " + rs.getString("mark"));
// Update the record
String query1="UPDATE student set mark=mark+10 where id=3";
st.executeUpdate(query1);
System.out.println("Data updated..");
// Display the record
rs=st.executeQuery("SELECT * FROM STUDENT WHERE id=3");
rs.next();
System.out.println(rs.getInt(1)+" "+rs.getString("name") + " " + rs.getString("mark"));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
The output is here
3 Arnold 85
Data updated..
3 Arnold 95
Updating multiple records
Here we have updated one record only by using WHERE condition. By changing the query part we can update multiple records.