2013-05-27 56 views
0

所以我正在学习JBDC,我正尝试通过java创建一个表。我测试了用户'calgar',它可以通过mysql命令创建一个表,但是当我尝试通过java实现相同时,它没有任何影响。没有创建表,但也没有错误或异常。有人有任何建议吗?CREATE TABLE没有任何影响JBDC

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){} 

     } 
+0

尝试'statement.executeUpdate(sql);' – Azad

回答

3

使用executeUpdate的数据库写入操作

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

除此之外,使用PreparedStatement保护自己免受SQL注入攻击。

+0

这工作。谢谢。 execute和excuteUpdate有什么区别? – Calgar99

+0

实际上,'execute'是用于当你不知道是否会有结果(并且更新计数也是结果)以及结果是什么(以及有多少)时。没有任何理由说明为什么一个CREATE TABLE会失败,执行execute()并且使用executeUpdate()来处理规范之后的驱动程序。 –