In our student table, we will insert one record of id=36. After adding 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();
// Adding record
String query1="INSERT INTO `my_tutorial`.`student` (`id`, `name`, `class`, `mark`, `sex`)"
+ " VALUES ('36', 'Test Name', 'Four', '73', 'male')";
st.executeUpdate(query1);
System.out.println("Data inserted..");
// Display the record
ResultSet rs=st.executeQuery("SELECT * FROM STUDENT WHERE id=36");
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
Number or records updated or added
By using this query we are changing the records of the table, so we can get back the number of rows or records affected by this query. This value as returned by MySQL we can capture and display to user. We can further use this number in our script.
We will store the return value of our method executeUpdate(), change in code is given here.
int no_rows=st.executeUpdate(query1);
System.out.println(no_rows + " rows of Data inserted..");