插入

时间:2018-06-02 08:02:45

标签: java sql-server jdbc

目前我正在使用MSSQL数据库学习Java JDBC。虽然所有步骤都已成功完成,但我无法使用下面的代码将数据插入到Stats表中。

代码是:从Entity表中获取数据,将其存储到Collection中。最后将该集合中的数据提供给Stats表。

代码insertCommand.executeUpdate()返回1,但表Stats不包含代码尝试插入的任何数据。

为什么会这样?

protected void FillStats(Connection connection) throws SQLException {
    PreparedStatement selectCmd = DatabaseHelper.createCommand(connection,
            "Select Id, Created, CreatedBy, Updated, UpdatedBy from Entity");
    System.out.println("A SQL statement has been created to retrieving data from Entity table.");
    List<Object[]> list = new ArrayList<Object[]>();
    try (ResultSet results = selectCmd.executeQuery()) {
        int numberOfObject = 0;
        System.out.println(">>> Start getting data from Entity table.");
        while (results.next()) {
            list.add(new Object[] { results.getInt(1), results.getDate(2), results.getString(3), results.getDate(4),
                    results.getString(5) });
            ++numberOfObject;
        }
        System.out.println("Total number of records retrieved: " + numberOfObject);
    }

    for (Object[] media : list) {
        PreparedStatement insertCmd = DatabaseHelper.createCommand(connection,
                "Insert into Stats ([Id], [Created], [CreatedBy], [Updated], [UpdatedBy]) values (?, ?, ?, ?, ?)");
        insertCmd.setInt(1, (int) media[0]);
        insertCmd.setDate(2, (Date) media[1]);
        insertCmd.setString(3, (String) media[2]);
        insertCmd.setDate(4, (Date) media[3]);
        insertCmd.setString(5, (String) media[4]);

        int updated = insertCmd.executeUpdate();
        if (updated > 0) {
            System.out.println("success");
        } else {
            System.out.println("Stuck somewhere");
        }
    }
}

表统计创建命令:

createCommand(con, "create table Stats "
            + "(Id INT not null, "
            + "Created DATETIME not null, "
            + "CreatedBy NVARCHAR(255) not null, "
            + "Updated DATETIME null, "
            + "UpdatedBy NVARCHAR(255) null, "
            + "primary key (Id))").execute()

表实体:

CREATE TABLE [Entity](
    [Id] [int] NOT NULL,
    [Version] [int] NOT NULL,
    [Name] [nvarchar](255) NOT NULL,
    [Description] [nvarchar](max) NULL,
    [Properties] [nvarchar](max) NULL,
    [TypeId] [int] NOT NULL,
    [TypeVersionId] [int] NOT NULL,
    [Created] [datetime] NOT NULL,
    [CreatedBy] [nvarchar](255) NOT NULL,
    [Updated] [datetime] NULL,
    [UpdatedBy] [nvarchar](255) NULL,
PRIMARY KEY 
(
    [Id] ASC
)) 

2 个答案:

答案 0 :(得分:0)

我查看了MySQL的文档,因为我看到你不能在方括号中给出列名。您需要将查询编写为

Insert into TableName (column1 , column2 , column3) values (value1 , value2 , value3);

当您使用与列数相同数量的值时,您可以直接将其值作为

Insert into TableName values (your values);

答案 1 :(得分:0)

我找到了一些可能有帮助的东西。您已将Created和Updated声明为DATETIME,这需要Timestamp而不是Date。 您还要在每个循环上为insert命令创建PreparedStatement,在循环之前尝试它。我还建议在退出之前关闭DB对象。所以我用这段代码成功地尝试了它:

protected void FillStats(Connection connection) throws SQLException {
    PreparedStatement selectCmd = connection.prepareStatement("Select Id, Created, CreatedBy, Updated, UpdatedBy from Entity");

    System.out.println("A SQL statement has been created to retrieving data from Entity table.");
    List<Object[]> list = new ArrayList<Object[]>();
    try (ResultSet results = selectCmd.executeQuery()) {
        int numberOfObject = 0;
        System.out.println(">>> Start getting data from Entity table.");
        while (results.next()) {
            list.add(new Object[]{results.getInt(1), results.getTimestamp(2), results.getString(3), results.getTimestamp(4),
                results.getString(5)});
            ++numberOfObject;
        }
        System.out.println("Total number of records retrieved: " + numberOfObject);
        results.close();
        selectCmd.close();
    }

    PreparedStatement insertCmd = connection.prepareStatement("Insert into Stats ([Id], [Created], [CreatedBy], [Updated], [UpdatedBy]) values (?, ?, ?, ?, ?)");
    for (Object[] media : list) {

        insertCmd.setInt(1, (int) media[0]);
        insertCmd.setTimestamp(2, (Timestamp) media[1]);
        insertCmd.setString(3, (String) media[2]);
        insertCmd.setTimestamp(4, (Timestamp) media[3]);
        insertCmd.setString(5, (String) media[4]);

        int updated = insertCmd.executeUpdate();
        if (updated > 0) {
            System.out.println("success");
        } else {
            System.out.println("Stuck somewhere");
        }
    }
    insertCmd.close();
}