Link to home
Start Free TrialLog in
Avatar of bhomass
bhomass

asked on

programmatically create an mysql table from java

I need to create a mysql database from inside a java program. the usu jdbc api does not work, since you can not establish a connection before the database exists.

please tell me how to go about it.
Avatar of Kim Ryan
Kim Ryan
Flag of Australia image

You just need to create a text streing containg the correct SQL statements , for example
"create table x (a integer, b char(3), c varchar(20))"
Then you need to execute that statement by connecting to the mysql dtabase, and supplying username, password etc. There should be some java library or ODBC module to do this.

PreparedStatmenet pst = connection.prepareStatment("SQL Statment that create a table");
 
pst.executeQuery();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of bhomass
bhomass

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
after downloading mysql driver for java from here ,,,
http://dev.mysql.com/downloads/connector/j/5.1.html
u can also see this site
http://bobcat.webappcabaret.net/javachina/scjd/team/mysql.htm

use the following code
import java.sql.*;
 
   public class connect
   {
       public static void main (String[] args)
       {
           Connection connection = null;
           Statement statement=null;
 
           try{
   		
   		
	String dataSourceName = "DataBaseName";
        String dbURL = "jdbc:mysql://localhost/" + dataSourceName;
        Class.forName ("org.gjt.mm.mysql.Driver").newInstance ();
        connection= DriverManager.getConnection(dbURL, "",""); 
         statement = connection.createStatement();
         
         
   
         	}
         	catch (Exception err) {
        System.out.println( "Error: " + err );
    }
          
       }
       
       
   }
   

Open in new window