6:48 pm - Thursday April 24, 2014

Statement CREATE TABLE Example program in java Jdbc mysql database

Create statement:

This tutorial explains how to Create 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 .  The following codes in this java tutorial explain how to Create a table named staff with columns as  Fields, Type, Null, Key, Default, Extra .

Java code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
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 stmt = conn.createStatement();
			String sql = "create table staff(name varchar(25),department varchar(5),subject_name varchar(25))";
			stmt.executeUpdate(sql);
			System.out.println("CreateTable 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:

                CreateTable successfully.

Filed in: Z-A All Java Codes

Comments are closed.

Social Widgets powered by AB-WebLog.com.