简体   繁体   English

BinaryData无法转换为java.lang.Integer

[英]BinaryData cannot be cast to java.lang.Integer

I'm trying to recreate this program from a textbook. 我正在尝试从教科书中重新创建该程序。 The textbook uses the jdbc::odbc bridge so I changed it to ucanaccess. 教科书使用了jdbc :: odbc桥,因此我将其更改为ucanaccess。 It also used longbinary for the password type and that wasn't recognizable to I changed it to just binary. 它还将longbinary用作密码类型,无法识别,我将其更改为仅二进制。 This is the output I'm receiving: 这是我收到的输出:

Dropping indexes & tables ... 删除索引和表...

Could not drop primary key on UserStocks table: UCAExc:::4.0.2 unexpected token: ON 无法在UserStocks表上删除主键:UCAExc ::: 4.0.2意外令牌:开

Creating tables ............ 创建表.........

Creating Stocks table with primary key index... 创建具有主键索引的Stocks表...

Creating Users table with primary key index... 使用主键索引创建Users表...

Creating UserStocks table ... 创建UserStocks表...

Creating UserStocks table primary key index... 正在创建UserStocks表主键索引...

Exception inserting user: UCAExc:::4.0.2 net.ucanaccess.triggers.TriggerException: org.hsqldb.types.BinaryData cannot be cast to java.lang.Integer net.ucanaccess.triggers.TriggerException: org.hsqldb.types.BinaryData cannot be cast to java.lang.Integer 异常插入用户:UCAExc :::: 4.0.2 net.ucanaccess.triggers.TriggerException:org.hsqldb.types.BinaryData无法转换为java.lang.Integer net.ucanaccess.triggers.TriggerException:org.hsqldb.types.BinaryData无法转换为java.lang.Integer

Database created. 数据库已创建。

Displaying data from database... 正在显示数据库中的数据...

Users table contains: 用户表包含:

Stocks table contains no records. 库存表不包含任何记录。

UserStocks table contains no records. UserStocks表不包含任何记录。

Here's the code: 这是代码:

 import java.sql.*;
import java.io.*;

public class MakeDB
{
public static void main(String[] args) throws Exception
{
    Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

    String url = "jdbc:ucanaccess://C:/Users/Sarah/workspace/StockTracker/StockTracker.mdb";

    Connection con = DriverManager.getConnection(url);
    Statement stmt = con.createStatement();

    // The following code deletes each index and table, if they exist.
    // If they do not exist, a message is displayed and execution continues.
    System.out.println("Dropping indexes & tables ...");

    try
    {
        stmt.executeUpdate("DROP INDEX PK_UserStocks ON UserStocks");

    }
    catch (Exception e)
    {
        System.out.println("Could not drop primary key on UserStocks table: "
                          + e.getMessage());
    }

    try
    {
        stmt.executeUpdate("DROP TABLE UserStocks");
    }
    catch (Exception e)
    {
        System.out.println("Could not drop UserStocks table: "
                          + e.getMessage());
    }

    try
    {
        stmt.executeUpdate("DROP TABLE Users");
    }
    catch (Exception e)
    {
        System.out.println("Could not drop Users table: "
                          + e.getMessage());
    }

    try
    {
        stmt.executeUpdate("DROP TABLE Stocks");
    }
    catch (Exception e)
    {
        System.out.println("Could not drop Stocks table: "
                          + e.getMessage());
    }

    ///////// Create the database tables /////////////
    System.out.println("\nCreating tables ............");

    // Create Stocks table with primary key index
    try
    {
        System.out.println("Creating Stocks table with primary key index...");
        stmt.executeUpdate("CREATE TABLE Stocks ("
                          +"symbol TEXT(8) NOT NULL "
                          +"CONSTRAINT PK_Stocks PRIMARY KEY, "
                          +"name TEXT(50)"
                          +")");
    }
    catch (Exception e)
    {
        System.out.println("Exception creating Stocks table: "
                          + e.getMessage());
    }

    // Create Users table with primary key index
    try
    {
        System.out.println("Creating Users table with primary key index...");
        stmt.executeUpdate("CREATE TABLE Users ("
                          +"userID TEXT(20) NOT NULL "
                          +"CONSTRAINT PK_Users PRIMARY KEY, "
                          +"lastName TEXT(30) NOT NULL, "
                          +"firstName TEXT(30) NOT NULL, "
                          +"pswd BINARY(254), "
                          +"admin BIT"
                          +")");
    }
    catch (Exception e)
    {
        System.out.println("Exception creating Users table: "
                          + e.getMessage());
    }

    // Create UserStocks table with foreign keys to Users and Stocks tables
    try
    {
        System.out.println("Creating UserStocks table ...");
        stmt.executeUpdate("CREATE TABLE UserStocks ("
                          +"userID TEXT(20) "
                          +"CONSTRAINT FK1_UserStocks REFERENCES Users (userID), "
                          +"symbol TEXT(8), "
                          +"CONSTRAINT FK2_UserStocks FOREIGN KEY (symbol) "
                          +"REFERENCES Stocks (symbol))");
    }
    catch (Exception e)
    {
        System.out.println("Exception creating UserStocks table: "
                          + e.getMessage());
    }

    // Create UserStocks table primary key index
    try
    {
        System.out.println("Creating UserStocks table primary key index...");
        stmt.executeUpdate("CREATE UNIQUE INDEX PK_UserStocks "
                          +"ON UserStocks (userID, symbol) "
                          );
    }
    catch (Exception e)
    {
        System.out.println("Exception creating UserStocks index: "
                          + e.getMessage());
    }


    // Create one administrative user with password as initial data
    String userID = "admin01";
    String firstName = "Default";
    String lastName = "Admin";
    String initialPswd = "admin01";
    Password pswd = new Password(initialPswd);
    boolean admin = true;

    PreparedStatement pStmt =
               con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?)");
    try
    {
        pStmt.setString(1, userID);
        pStmt.setString(2, lastName);
        pStmt.setString(3, firstName);
        pStmt.setBytes(4, serializeObj(pswd));
        pStmt.setBoolean(5, admin);
        pStmt.executeUpdate();
    }
    catch (Exception e)
    {
        System.out.println("Exception inserting user: "
                          + e.getMessage());
    }

    pStmt.close();

    // Read and display all User data in the database.
    ResultSet rs = stmt.executeQuery("SELECT * FROM Users");

    System.out.println("Database created.\n");
    System.out.println("Displaying data from database...\n");
    System.out.println("Users table contains:");

    Password pswdFromDB;
    byte[] buf = null;

    while(rs.next())
    {
        System.out.println("Logon ID         = "
                          + rs.getString("userID"));
        System.out.println("First name       = "
                          + rs.getString("firstName"));
        System.out.println("Last name        = "+rs.getString("lastName"));
        System.out.println("Administrative   = "+rs.getBoolean("admin"));
        System.out.println("Initial password = "+initialPswd);


        buf = rs.getBytes("pswd");
        if (buf != null)
        {
            System.out.println("Password Object  = "
                              + (pswdFromDB=(Password)deserializeObj(buf)));
            System.out.println("  AutoExpires    = "+ pswdFromDB.getAutoExpires());
            System.out.println("  Expiring now   = "+ pswdFromDB.isExpiring());
            System.out.println("  Remaining uses = "
                              + pswdFromDB.getRemainingUses()+"\n");
        }
        else
            System.out.println("Password Object  = NULL!");
    }

    rs = stmt.executeQuery("SELECT * FROM Stocks");
    if(!rs.next())
        System.out.println("Stocks table contains no records.");
    else
        System.out.println("Stocks table still contains records!");

    rs = stmt.executeQuery("SELECT * FROM UserStocks");
    if(!rs.next())
        System.out.println("UserStocks table contains no records.");
    else
        System.out.println("UserStocks table still contains records!");

    stmt.close(); // closing Statement also closes ResultSet

} // end of main()

// Method to write object to byte array and then insert into prepared statement
public static byte[] serializeObj(Object obj)
                          throws IOException
{
    ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
    ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);

    objOStream.writeObject(obj); // object must be Serializable
    objOStream.flush();
    objOStream.close();
    return baOStream.toByteArray(); // returns stream as byte array
}

// Method to read bytes from result set into a byte array and then
// create an input stream and read the data into an object
public static Object deserializeObj(byte[] buf)
                        throws IOException, ClassNotFoundException
{
    Object obj = null;

    if (buf != null)
    {
      ObjectInputStream objIStream =
        new ObjectInputStream(new ByteArrayInputStream(buf));

      obj = objIStream.readObject(); // throws IOException, ClassNotFoundException
    }
    return obj;
}

} }

Any help with this would be much appreciated! 任何帮助,将不胜感激!

You have some wrong logic in your program : 您的程序中有一些错误的逻辑:

step 1. Drop the index 步骤1.删除索引
step 2. Drop table 步骤2.删除表
step 3. Create the table 步骤3.创建表

In step 1 it is logic that your table is not exist so the index also not exit, so for that you get this exception. 步骤1中 ,逻辑上是您的表不存在,因此索引也不会退出,因此您将获得此异常。


Not like tables or database you can check if your index exist or not, to avoid this problem you don't need to drop your index , because when you drop the table, also the indexes will doped check this ( Does dropping a table in MySQL also drop the indexes? ). 与表或数据库不同,您可以检查索引是否存在,为避免此问题, 您无需删除索引 ,因为在删除表时,索引也会被掺杂( 在MySQL中删除表)还删除索引? )。


Note : to avoid problems when you create and drop database, tables, you have use IF NOT EXISTS , for example : 注意:为避免在创建和删除数据库表时出现问题,请使用IF NOT EXISTS ,例如:

DROP TABLE Stocks IF EXISTS
CREATE TABLE Stocks IF NOT EXISTS (...)

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

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