Share on Google+Share on Google+

JDBC Insert Prepared Statement

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.


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
		// 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
			// 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");

		} catch (ClassNotFoundException e) {
			System.out.println("Class Not found Exception cought");
		} catch (SQLException e) {
		} catch (Exception e) {
		} finally {
			// Closing the connection
			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



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.