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;
			try
			{
				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
				Connection con;
				con = DriverManager.getConnection(url,id,pd);
				Statement st = con.createStatement();
				PreparedStatement pst = con.prepareStatement(query);
				pst.setString(1,arg[0]);
				pst.setString(2,arg[1]);
				pst.executeUpdate();
				 res = st.executeQuery("select * from players");
				while(res.next())
				{
					System.out.println(res.getString(2)+"   "+res.getString(3)+"  ");
				}
			}
			catch(Exception e)
			{
				System.out.print(e);
			}	
		}
}

preparedstatementDemo1
Click here to download the source code

Advertisements

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 Master's 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:

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s