Zach443
Zach443

Reputation: 311

How to create a MySQL table in Java?

I am logging something to a MySQL database with a Java program, and I was wanting to create a table if the one I wanted to use did not exist. How would I got about creating a table through Java? (If clerification is needed, please say so).

P.S. before you say this question is a duplicate of this question, that question did not answer mine.

Upvotes: 0

Views: 2563

Answers (2)

Josef E.
Josef E.

Reputation: 2219

First you would need a StringBuilder to create the sql statement.

Example:

StringBuilder sql = new StringBuilder("IF NOT EXISTS (CREATE TABLE REGISTRATION ");
               sql.append("(id INTEGER not NULL, ");
               sql.append(" first VARCHAR(255), "); 
               sql.append(" last VARCHAR(255), "); 
               sql.append(" age INTEGER, ");
               sql.append(" PRIMARY KEY ( id )))");

Then take that StringBuilder and get Connection to a db

Example:

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to a selected database...");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

System.out.println("Creating table in given database...");
Statement stmt = conn.createStatement();

stmt.executeUpdate(sql.toString());

Source: here

Upvotes: 2

user2007447
user2007447

Reputation: 133

If you have already made a connection then there must be a Connection object in your code. This is used to send queries and updates to your database.

So to create a table you have to construct the SQL command in a regular String like so:

String sql = "CREATE TABLE tab1 (number1 INTEGER, number2 TINYINT, name CHAR(64))"

Now you have to send it to the database like so:

/*    connection is your Connection object    */
/*    you have to prepare the statement and store it in a PreparedStatement object    */
PreparedStatement stmt = connection.prepareStatement(sql);
/*    this line does the database update    */
stmt.executeUpdate();

This is it! The table tab1 has been created!

Upvotes: 0

Related Questions