Thursday 25 July 2019

Java MySQL Insert Example using Prepared Statement

                      In this post, we will see Java MySQL Insert Example using Prepared Statement.

                In previous post https://www.comrevo.com/2017/07/jdbc-code-to-insert-data-into-mysql-database.html, we have seen how to insert records (rows) into MySQL database. Here, we will see how to use PreparedStatement. 

For details, watch following video:

Watch on YouTube: https://www.youtube.com/watch?v=S6mJpp5Dg7c

What is the need of Prepared Statement?:
               Sometimes we need to implement same query multiple times e.g. insert query to add multiple records into table. In this situation, only data get changed while the syntax for SQL query remains same. Here, unnecessarily we compile the same query multiple times. To avoid this, we have to use PreparedStatement.

What is PreparedStatement?
               PreparedStatement is an Interface. Stament interface is extended in PreparedStament interface.

               Here sdldb is the database name. User name is sdl and password is sdl123. This program is for inserting records (rows) into MySQL database table student.
              
Program (JdbcInsertPS.java):
 import java.sql.*;

class JdbcInsertPS
{
public static void main(String args[]) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sdldb","sdl","sdl123");
PreparedStatement st=con.prepareStatement("insert into student values(?,?,?,?)");
st.setInt(1,2301);
st.setString(2,"SE");
st.setString(3,"COEP");
st.setString(4,"Pune");

int i=st.executeUpdate();

st.setInt(1,3301);
st.setString(2,"TE");
st.setString(3,"SGGS");
st.setString(4,"Nanded");

int j=st.executeUpdate();

ResultSet rs=st.executeQuery("select * from student");
while(rs.next())
{
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+" ");
System.out.print(rs.getString(4)+" ");

System.out.println("\n");
}

rs.close();
st.close();
con.close();
}
}
               
Output:
parag@parag-Inspiron-N4010:~/Desktop/programs/jdbc$ javac JdbcInsertPS.java
parag@parag-Inspiron-N4010:~/Desktop/programs/jdbc$ java JdbcInsertPS
1221 SE PICT Pune

3221 TE VJTI Mumbai

1201 se vjti mumbai

3201 te coep Pune

4201 be wce Sangli

2301 SE COEP Pune

3301 TE SGGS Nanded




                       Check jdbc code for fetching data from database in this post: http://www.comrevo.com/2017/07/jdbc-code-to-retrieve-data-from-mysql-database.html

No comments:

Post a Comment