Java J2ee Tutorials

Creating a Database Table

Monday, February 6, 2012

package com;

import java.sql.*;

public class CreateTableExample {
public static void main(String args[]){
System.out.println("Creation Table Example");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Database Connected");
try {
Statement stmt = con.createStatement();
String table = "CREATE TABLE EMPLOYEE(emp_id integer, emp_name varchar(50) )";
stmt.executeUpdate(table);
System.out.println("Table created successfully");
}
catch (Exception e){
System.out.println("Sorry!! Table already exists.");
}
con.close();
System.out.println("Connection Closed");
}
catch (Exception e){
System.out.println("Error: " +e);
e.printStackTrace();
}
}
}
========
Out Put

Creation Table Example
Database Connected
Table created successfully
Connection Closed

Free Career Predictions

0 comments:

Post a Comment