Wednesday 11 December 2013

creating table in MYSQL

//using Mysql and database name is test, so create one database in mysql(ex: in this prog
//i have already created one database in 'test'. If u wont create u get error
import java.sql.*;//jdbc api
public class CreateTable
{
public static void main(String args[]) throws SQLException, ClassNotFoundException
{
//get connection
Connection con=prepareConnection();
//obtain a statement
Statement st=con.createStatement();
String q= "CREATE TABLE `test`.`mytable`( `id` INT(3) NOT NULL AUTO_INCREMENT, `name` VARCHAR(20), `add` VARCHAR(40), PRIMARY KEY (`id`) )";


//execute the query
st.executeUpdate(q);
System.out.println("Table created successfully");
con.close();


}
public static Connection prepareConnection() throws SQLException, ClassNotFoundException
{
String d="com.mysql.jdbc.Driver";//driver class name
String url="jdbc:mysql://localhost:3306/test";
String uname="root";
String pwd="admin";
//load driver class
Class.forName(d);
//obtain the connection
Connection con=DriverManager.getConnection(url,uname,pwd);
return(con);

}
}
/* TO RUN THIS PROGRAM

1) Install MySql , i gave my username is "root", password is "admin"
2) 2) download jar files of MySql: "mysql-connector-java-5.1.18-bin.jar" and save in any folder i saved this jar file in "D:\softwares\MySQL\new"
3) set the class path:
example

D:\jdbc>set classpath=D:\softwares\MySQL\new\mysql-connector-java-5.1.18-bin.jar
;.;
4) now compile the program

D:\jdbc>javac CreateTable.java
5) execute the program
D:\jdbc>java CreateTable




No comments:

Post a Comment