2:28 am - Friday April 19, 2019

Statement INSERT Example program in java Jdbc mysql database

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

SQL INSERT INTO Statement:

This tutorial explains how to insert  a single row into a table in mysql using java statement example, Load the mysql driver using Class.forName method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and use executeUpdate to execute the query.  If we wants to add a new  record into the table or to add a new row, just use this following code to update the table with new record.

create table:

create table student(Roll_No int(5),Name varchar(25),

Department varchar(7),Address varchar(30));

Query OK, 0 rows affected (0.06 sec)

Input:

Java code:

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

public class CreateTable {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String Driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/test";
		String uName ="root";
		String pwd = "root";
		Connection conn=null;

		try {
			Class.forName(Driver).newInstance();
			conn = DriverManager.getConnection(url, uName, pwd);
			Statement st= conn.createStatement();
			String sql="insert into student values('101','suresh','cse','chennai')";
			st.executeUpdate(sql);
			System.out.println("Data Inserted sucessfully");

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

OUTPUT:

 

 

Data Inserted successfully

 

 

Filed in: Z-A All Java Codes

Comments are closed.