Home Tutorial Java Jdbc JDBC Insert Statement Example

 
 

Share on Google+Share on Google+
JDBC Insert Statement Example
Posted on: October 13, 2010 at 12:00 AM
Advertisement
In this tutorial you will learn how to insert data into the table through JDBC simple Statement

JDBC Insert Statement Example

JDBC Insert statement allow you to insert record into the table of the database. This tutorial shows you that how to load database driver, get connection t the database and insert record to the database.

At first create table named student in MySql database and inset values into it as.

CREATE TABLE student (
RollNo int(9)  PRIMARY KEY NOT NULL,
Name tinytext NOT NULL,
Course varchar(25) NOT NULL,
Address text
 );

JDBCInsertExample.java

package roseindia.net;

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

public class JDBCInsertExample {
	public static void main(String[] args) throws SQLException {
		Connection con = null; // connection reference variable for getting
								// connection
		Statement stmt = null; // Statement reference variable for query
								// Execution
		String conUrl = "jdbc:mysql://localhost:3306/";
		String driverName = "com.mysql.jdbc.Driver";
		String databaseName = "student";
		String usrName = "root";
		String usrPass = "root";
		try {
			// Loading Driver
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
		}
		try {
			// Getting Connection
			con = DriverManager.getConnection(conUrl + databaseName, usrName,
					usrPass);
			// Creating Statement for query execution
			stmt = con.createStatement();
			// creating Query String
			String query = "INSERT INTO student values(1,'Vinay','MCA','Mumbai')";
			// Updating Table
			stmt.executeUpdate(query);
			System.out.println("Table Updated Successfully....");
		} catch (Exception e) {
			System.out.println(e.toString());
		} finally {
			// Closing Connection
			con.close();
			stmt.close();
		}
	}
}
When you run this application it will display message as shown below:

Table Updated Successfully....

Download this example code

Advertisement

Related Tags for JDBC Insert Statement Example:


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.

Posted on: October 13, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com