【问题标题】:Inserting 0 for an auto-incrementing column in mysql为mysql中的自动递增列插入0
【发布时间】:2018-02-05 22:47:16
【问题描述】:

我使用的是 slick 3.2.1

我需要将“0”插入自动递增的列 (MySQL)。

我写了这段代码

val foo = Foo(0, "FOO")
val fooQuery = Tables.FooTable forceInsert  foo
Await.result(db.run(fooQuery), Duration.Inf)

我希望forceinsert 将准确的值 0 放在列中,而不是使用数据库提供的增量值。

上面的代码运行良好。但是当我进入数据库时​​,我看到 ID 是 1。所以它没有强制 id 为 0。它仍在使用数据库提供的值。

【问题讨论】:

    标签: scala slick slick-3.0


    【解决方案1】:

    如果您的值低于现有值,您将无法插入任何自动递增的列。如果我相信桌子是空的,你可以这样做。

    【讨论】:

    • 我假设有现有数据。
    • 我在加载数据之前截断了表格。
    • 这个答案是否有帮助:stackoverflow.com/questions/1142472/…
    • 是的,当我从 mysql 命令行尝试时有效。知道如何使用 Slick 做同样的事情吗?
    • 我唯一能想到的就是尝试使用纯 SQL 查询
    【解决方案2】:

    此代码正在运行。

    对于自动增量,在 scala 中为相应的参数值添加零并创建具有自动增量字段 [id] 的表

    **/*Table creation*/**
    
    CREATE TABLE `recommendation` 
    (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `product_id` int(11) DEFAULT NULL,
        `rec_product_id` int(11) DEFAULT NULL,
        `color_id` int(11) DEFAULT '1',
        `uiposition` int(11) DEFAULT '0',
    
        PRIMARY KEY (`id`)
    )
    
    /* scala Code */
    
    val insertSql = """
                          |INSERT INTO `wellness`.`recommendation` (`id`, `product_id`, `rec_product_id`, `color_id`, `uiposition`)
                          |VALUES (?,?,?,?,?)
                        """.stripMargin
    
    
        val preparedStmt: sql.PreparedStatement = conn.prepareStatement(insertSql)
    
        preparedStmt.setInt (1, 0)//Auto increment in scala**
        preparedStmt.setInt (2, vproid)
        preparedStmt.setInt (3, recoid.toInt)
        preparedStmt.setInt    (4, 1)
        preparedStmt.setInt    (5, uipos)
    

    【讨论】:

      猜你喜欢
      • 2011-08-23
      • 2011-08-20
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      相关资源
      最近更新 更多