Share on Google+Share on Google+

JDBC Insert Prepared Statement

Advertisement
In this tutorial you will learn how to Insert value in MySQL database table using PreparedStatement

JDBC Insert PreparedStatement

PreparedStatement represents a precompiled SQL statement. It is alternative to Statement

At first Create named student a table in MySQL database as

CREATE TABLE `student` (
`rollno` int(11) NOT NULL,
`name` varchar(50) default NULL,
`course` varchar(20) default NULL,
PRIMARY KEY (`rollno`)
)

following is an example of JDBC PreparedStatement with MySql database.

MySqlPreparedStatement.java

package roseindia.net;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySqlPreparedStatement {
	public static void main(String[] args) throws SQLException {
		System.out.println("MySQL Insert PreparedStatement Example.");
		Connection conn = null;
		PreparedStatement ptmt = null;
		// 3306 is the default port number of MySQL
		// 192.168.10.13 is host address of the MySQL database
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "student";
		String driver = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		try {
			// Load the driver
			Class.forName(driver);
			// Get a connection
			conn = DriverManager
					.getConnection(url + dbName, userName, password);
			System.out.println("Connected to the database");
			// Create a query String
			String query = "INSERT INTO STUDENT(rollno,name,course) VALUES(?,?,?)";
			// Create a PreparedStatement
			ptmt = conn.prepareStatement(query);
			ptmt.setInt(1, 8);
			ptmt.setString(2, "Dragon");
			ptmt.setString(3, "M.Tech");
			ptmt.executeUpdate();

		} catch (ClassNotFoundException e) {
			System.out.println("Class Not found Exception cought");
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// Closing the connection
			conn.close();
			ptmt.close();
			System.out.println("Database Updated Successfully");
			System.out.println("Disconnected from database");
		}
	}
}

When you run this application it will display message as shown below:


MySQL Insert PreparedStatement Example.
Connected to the database
Database Updated Successfully
Disconnected from database

Download this example code

Advertisements

Advertisement

Posted on: November 18, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.