无法确定为什么此SQL语句不会执行(Derby)

时间:2017-06-29 08:47:59

标签: java sql derby

我的表格设置如下,似乎正确创建。 (没有抛出异常)

    String sqlString = String.format(
            "CREATE TABLE %s(%s BIGINT, 
            %s VARCHAR(%d), 
            %s VARCHAR(%d), 
            %s VARCHAR(%d), 
            %s INT, 
            %s INT, 
            %s BIGINT, 
            PRIMARY KEY (%s))",
                //
                TABLE_NAME, //
                Column.ID.name, //
                Column.MAKE.name, Column.MAKE.length, //
                Column.MODEL.name, Column.MODEL.length, //
                Column.SERIAL_NUMBER.name, Column.SERIAL_NUMBER.length, //
                Column.YEAR.name, //
                Column.MILEAGE.name, //
                Column.CUSTOMER_ID.name, //
                Column.ID.name);

我想插入以下内容:

String sqlString = String.format(//
            "INSERT INTO %s values(?, ?, ?, ?, ?, ?, ?)", TABLE_NAME);
    boolean result = execute(sqlString, //
            motorcycle.getId(), // long
            motorcycle.getMake(), // String
            motorcycle.getModel(), // String
            motorcycle.getSerialNumber(), // String
            motorcycle.getYear(), // int
            motorcycle.getMileage(), // int
            motorcycle.getCustomerId()); //long

execute(sqlString, args[])返回false,但不会抛出任何异常。 derby.log也没有关于出了什么问题的信息。

我使用了错误的SQL数据类型吗?

编辑:

execute(sqlString, args[])方法在Dao超类中,适用于其他子类。

代码如下:

 protected boolean execute(String preparedStatementString, Object... args) throws SQLException {
        LOG.debug(preparedStatementString);
        boolean result = false;
        PreparedStatement statement = null;
        try {
            Connection connection = Database.getConnection();
            statement = connection.prepareStatement(preparedStatementString);
            int i = 1;
            for (Object object : args) {
                statement.setObject(i, object);
                i++;
            }

            statement.executeUpdate();
            result = true;
        } finally {
            close(statement);
        }

        return result;
    }

2 个答案:

答案 0 :(得分:2)

来自PreparedStatement javadoc for execute(String sql)

  

返回:

     

如果第一个结果是ResultSet对象,则为true;如果是更新计数或没有结果,则为false

很可能你的表创建成功了,你刚刚获得false,因为没有结果可供阅读。

在评论中提及a_horse_with_no_name时,使用PreparedStatement.executeUpdate()更适合此类陈述。

答案 1 :(得分:1)

我遇到了类似的问题,但我的错误是表格不存在而且我的代码是为了创建表格,如果它不存在,所以经过一些研究我发现之后create=true我需要升级数据库,即upgrade=true

这是我的代码:

import java.sql.*;
import javax.swing.JOptionPane;

public final class DatabaseHandler {
private static DatabaseHandler handler;

private static final String DB_URL = 
"jdbc:derby:BookData;create=true;upgrade=true"; 
//connection to database
private static Connection conn = null;
//for creeat insert and oda mySql statements
private static Statement stm = null;

public DatabaseHandler() {
    createconnection();
    setupbookTable();
}



void createconnection(){
  try {

  Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
  System.out.println("Dis is a database connection error "+e);
      conn = DriverManager.getConnection(DB_URL);
  } catch (Exception e) {
  System.out.println("Dis is a database connection error "+e);
  }
 }

 void setupbookTable()
 {
  String TABLE_NAME = "BOOK";
  try {
      //use d object of connection to create a statement
      stm = conn.createStatement();
      //checks if table exist evytime d app is run
      DatabaseMetaData dmb = conn.getMetaData();
      ResultSet tables = dmb.getTables(null, null, TABLE_NAME.toUpperCase(), 
     null);
      if(tables.next())
      {
          System.out.println("Table" +TABLE_NAME+" already Exists");
      }
      else
      {
          stm.execute("CREATE TABLE " + TABLE_NAME + "("
                  +" id varchar(200) primary key,\n"
                  +" title varchar(200),\n"
                  +" writer varchar(200),\n"
                  +" printer varchar(200),\n"
                  +" isAvail boolean default true"
                  + ")");
      }

  } catch (SQLException e) {
      System.err.println(e.getMessage() +"---Setup Database");
  }
  finally
  {  
  }
}
public ResultSet execQuery(String query)
  {
      ResultSet result;
      try {
          stm = conn.createStatement();
          result = stm.executeQuery(query);
      }catch(SQLException ex)
      {
          System.out.println("Error in Database:execQuery" +ex.getLocalizedMessage());
          return null;
      }finally
      {
      }
      return result;
  }
 public boolean execAction(String qu)
{
   try {
       stm = conn.createStatement();
       stm.execute(qu);
       return true;
   } catch (SQLException e) {
       JOptionPane.showMessageDialog(null, "Error occured " +e.getMessage(), 
  " Error", JOptionPane.ERROR_MESSAGE);
       System.out.println("Exception at execQuery:dataHandler" 
  +e.getLocalizedMessage());
       return false;
   }
   finally
   {

   }
 }
}

我还为Actions和Query创建了一个n exec方法,这就是你使用它的方法:

  public class FXMLbookController implements Initializable {

  private Label label;
  @FXML
  private JFXTextField title;
  @FXML
  private JFXTextField id;
  @FXML
  private JFXTextField writer;
  @FXML
  private JFXTextField printer;
  @FXML
   private JFXButton save;
  @FXML
  private JFXButton cancel;
  DatabaseHandler database;

  @Override
  public void initialize(URL url, ResourceBundle rb) {
     database = new DatabaseHandler();
}    

@FXML
private void addBook(ActionEvent event) {
    String bookId = id.getText();
    String bookTitle = title.getText();
    String bookPublisher = printer.getText();
    String bookAuthor = writer.getText();
    if(bookId.isEmpty() || bookTitle.isEmpty() || bookPublisher.isEmpty() || 
    bookAuthor.isEmpty())
    {
        JOptionPane.showMessageDialog(null, "No field must be left empty", 
  "Error Occured", JOptionPane.ERROR_MESSAGE);
        return;
     }
    else
    {
        /*+" id varchar(200) primary key,\n"
                  +" title varchar(200),\n"
                  +" writer varchar(200),\n"
                  +" printer varchar(200),\n"
                  +" intcode varchar(100),\n"
                  +" isAvail boolean default true"*/
        String quIn = "INSERT INTO BOOK VALUES("+
                "'" + bookId+"'," +
                "'" + bookTitle+"',"+
                "'" +bookAuthor+ "',"+
                "'" + bookPublisher+"',"+
                "'" +"true"+"'"+
                ")";
        System.err.println(quIn);
        if(database.execAction(quIn))
        {
            JOptionPane.showMessageDialog(null, "Success", "Success", 
    JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Error: ", " Not inserted", 
  JOptionPane.ERROR_MESSAGE);
        };
    }
}

@FXML
private void cancel(ActionEvent event) {
}

}