Java program for Inserting rows using preparedstatement

In our earlier post we have learned about making connection from a Java program to the databases.But the drawback of just using createStatement() and excuteuery(),is that we can request for run time values and then insert it into the database.

To overcome this drawback,there is a special type of statements called as PreparedStatement for inserting the values into the database which are given through command line arguments.These statements are used to insert rows into the database with values given through command line arguments.
For creating a prepared statement,we need to create an object to the class PreparedStatement and assign the query init.After getting the values and inserting it into the query we need to update the database.For this we use the function executeUpdate();

We shall write a program to demonstrate the use of prepared statement.

import java.sql.*;
class preparedstatementDemo1
	public static void main(String arg[]) throws Exception
			String id="";
			String pd="";
			String url="jdbc:odbc:company";
			String query="INSERT INTO players (PlayerName,PlayerAge) VALUES (? , ?)";
			ResultSet res;
				Connection con;
				con = DriverManager.getConnection(url,id,pd);
				Statement st = con.createStatement();
				PreparedStatement pst = con.prepareStatement(query);
				 res = st.executeQuery("select * from players");
					System.out.println(res.getString(2)+"   "+res.getString(3)+"  ");
			catch(Exception e)

Click here to download the source code


About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s