简体   繁体   English

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

[英]Cannot determine why this SQL statement won't execute (Derby)

My table is set up like this and seems to get created properly. 我的表设置如下,似乎正确创建。 (no exceptions are thrown) (没有抛出异常)

    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);

I am trying to insert the following: 我想插入以下内容:

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[]) returns false , but no exceptions are thrown. execute(sqlString, args[])返回false ,但不抛出任何异常。 derby.log has no information about what's going wrong either. derby.log也没有关于出了什么问题的信息。

Am I using the wrong SQL data types? 我使用错误的SQL数据类型吗?

Edit: 编辑:

The execute(sqlString, args[]) method is in the Dao super-class and works fine for the other sub-classes. execute(sqlString, args[])方法在Dao超类中,适用于其他子类。

The code is as follows: 代码如下:

 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;
    }

From the PreparedStatement javadoc for execute(String sql) : PreparedStatement javadoc for execute(String sql)

Returns: 返回:

true if the first result is a ResultSet object; 如果第一个结果是ResultSet对象,则为true;否则为false。 false if it is an update count or there are no results 如果是更新计数或没有结果,则返回false

Most likely your table creation succeded, you're just getting false because there's no result to read. 很可能你的表创建成功,你只是变得false因为没有结果可读。

As a_horse_with_no_name mentions in the comments, using PreparedStatement.executeUpdate() would be more appropriate for this kind of statement. 正如a_horse_with_no_name在注释中提到的那样,使用PreparedStatement.executeUpdate()会更适合这种语句。

I encountered a similar problem but mine was that the error was that the table doesn't exist and my code was meant to create the table if it doesn't exist so after some research I found out that after the create=true I needed to upgrade the database ie upgrade=true . 我遇到了类似的问题,但我的错误是表不存在,我的代码是为了创建表,如果它不存在所以经过一些研究我发现在create=true我需要升级数据库即upgrade=true

This is my code: 这是我的代码:

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
   {

   }
 }
}

I also created an n exec method for the Actions and Query and this is how you used it: 我还为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) {
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM