Calgar99
Calgar99

Reputation: 1688

CREATE TABLE has no affect JBDC

So I'm learning about JBDC and I am trying to create a table through java. I have tested the user 'calgar' which can create a table through mysql commands however when I try to implement the same through java It has no affect.No Table created but no errors or exceptions also. Does anybody have any suggestions?

public static void main(String[] args) {

        Connection connection = null;
        Statement statement = null; 

        try{
            System.out.println("Connecting to driver/database..");
             Class.forName("com.mysql.jdbc.Driver");
             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/firstdatabase","calgar","password");
             System.out.println("Connection successful");
             statement = connection.createStatement();
             statement.execute("CREATE TABLE books(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100),author VARCHAR(100),publisher VARCHAR(100))");


        }
        catch(ClassNotFoundException error){
            System.out.println("Class Not Found Error " + error.getMessage());
        }
       catch(SQLException error){
        System.out.println("SQL Error " + error.getMessage());
        }
        finally
        {
            if(connection != null)
                try{connection.close();}
                catch(SQLException ignore){}

            if(statement != null)
                try{statement.close();}
                catch(SQLException ignore){}

        }

Upvotes: 0

Views: 66

Answers (1)

Reimeus
Reimeus

Reputation: 159784

Use executeUpdate for database write operations

statement.executeUpdate("CREATE TABLE ...");

Aside from that, use PreparedStatement to protect yourself from SQL Injection attacks.

Upvotes: 3

Related Questions