Written by Sai Sandeep Thota on November 23, 2013 in Java > Programming

Insert Rows using Prepared Statements in Java

GET ALERTS:

Get our Latest updates delivered to your mailbox!

How do we Insert rows in a Database using a Java program? We simply write a INSERT query and execute it. For instance if we have to do it multiple times, it would be overhead to change the query multiple times. So PreparedStatements comes to our rescue here. We can Insert Rows using Prepared Statements in Java.

Prepared Statements are useful to take inputs from Command line during run time. You can read How to Connect to Access Database using Java here. All the objects and methods are explained in that article, We are using PreparedStatement class objects to insert data into the Database.

INSERT INTO products (productno, name, price) VALUES (?, ?, ?) the Question marks(?) in the query are filled up during run time by the values we enter in command line. pstat.setInt(1, args[0]); is used to get the first Integer that is entered in the command line and set it as the first question mark(first column) value. To set the value of 2nd column we use: pstat.setInt(2, args[1]);.

Insert Rows using Prepared Statements in Java

import java.sql.*;

public class myStorePrepared {
	public static void main(String args[])
	{
		ResultSet rs;
		String url = "jdbc:odbc:myStore";
		String username = "";
		String password = "";

		try
		{

			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

			Connection con;

			con = DriverManager.getConnection(url, username, password);

			Statement stat = con.createStatement();

			String query = "INSERT INTO products (productno, name, price) VALUES (?, ?, ?)";

			PreparedStatement pstat = con.prepareStatement(query);

			Integer x = Integer.valueOf(args[0]);

			pstat.setInt(1,x);
			pstat.setString(2, args[1]);
			pstat.setString(3, args[2]);

			pstat.executeUpdate();

			rs = stat.executeQuery("SELECT * FROM products");

			while(rs.next())
			{
				String row = rs.getString(1) + " " + rs.getString(2) + " Rs. " + rs.getString(3);
				System.out.println(row);
			}
		}

		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}

Output:
Insert Rows using Prepared Statements in Java

Download Source Code

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: