0

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.

2
  • Do you mean to use the "IF NOT EXISTS" clause in the CREATE statement? Commented Jun 5, 2014 at 20:46
  • It is indeed a duplicate. You should handle the exception in case the table already exists, but that shoul be covered in your code, not in the question/answer. Commented Jun 5, 2014 at 20:53

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe it would be wise to add if not exists to the create statement (just in case): create table if not exists REGISTRATION (...)
@Barranka or handle the exception. But looks like OP is too lazy to search for that.
0

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!

1 Comment

executeUpdate(). I am sorry, don't know what I was thinking. Is this a reason to downvote me?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.