PreparedStatement in JDBC

In my previous blog Getting started with Java Database Connectivity we had seen how to connect to MySQL using the JDBC API and also learnt how to execute queries on MySQL database using command line and using a java program. In this blog we will take a closer look at the JDBC Statement Classes.
Following mind map represents three types of statements classes that are provided by JDBC API to executing queries on database:

Statement_mind_map

We had used Statement in the previous blog Getting Started with JDBC. In this blog, we will be executing queries using PreparedStatement. Let’s get our hands dirty!



//importing sql package
import java.sql.*;
public class Database_connection {
	public static void main(String[] args) {
		Connection conn = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "test";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			// Load driver class into memory
			Class.forName(driver).newInstance();
			// Get Database Connection: getConnection() method                              returns object of concrete class of Connection Interface
			conn = DriverManager.getConnection(url+dbName, userName,                        password);
			// Executing Select statement/SQL using                                         PreparedStatement
			/*We are getting PreparedStatement object via                                   prepareStatement() method from Connection concrete class                        and we pass SQL query into prepareStatement() which we                          want to pre-compile. */
			PreparedStatement pstmt = conn.prepareStatement("Select                         * from users where name =?");
			/*setString method sets the designated parameter to the                         given Java String value.  First parameter number which                          says position of ?(question mark), and second parameter                         is value which will be replaced by that ?(question mark)                        */
			pstmt.setString(1, "Krishna");
			/* Executes the SQL query via calling the method execute                        Query() and it returns the ResultSet object which is                            generated by the query result. */
			ResultSet rs1 = pstmt.executeQuery();
			/* getString() is a method in ResultSet that retrieves                          the value of the designated column in the current row of                        this ResultSet as a String in the .*/
			while(rs1.next()){
			System.out.println(rs1.getString(1) + "------"+                                 rs1.getString(2) + "------" + rs1.getString(3));
			}
			// Executing Insert Statement using PreparedStatement
			PreparedStatement pstmt1 = conn.prepareStatement("insert                        into users values(?,?,?)");
			pstmt1.setString(1, "Jai");
			pstmt1.setString(2,"Maharashtra");
			pstmt1.setString(3,"M");
			/* executeUpate() is a method which is used to execute                          Insert, Update and Delete SQLs. This method returns the                         number of rows affected by the query.*/
			int i = pstmt1.executeUpdate();
			System.out.println(i);
			//Executing delete statement using PreparedStatement
			PreparedStatement pstmt2 = conn.prepareStatement("Delete                        from users where name =?");
			pstmt2.setString(1, "Jai");
			int j = pstmt2.executeUpdate();
			System.out.println(j);
		}catch(Exception e){
			e.printStackTrace();	
		}
	}
}

In this blog we have seen simple usage of PreparedStatement. In the future blogs we will play more around the database, till than Happy Learning!

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.