我很高兴找到this技术,但使用它似乎阻止我在行中自动递增id值。
是否有唯一的方法让id值在行中输入?
$db.execute("
INSERT INTO 'students'
SELECT 'Brett' AS 'first_name', 'Iton' AS 'last_name', 'M' AS 'gender', '1966-01-17' AS 'birthday', '415-879-54451' AS 'phone', DATETIME('now') AS 'created_at', DATETIME('now') AS 'updated_at'
UNION SELECT 'Lady','Gaga', 'F', '1970-03-17', '213-879-4545', DATETIME('now'), DATETIME('now')
UNION SELECT 'Former','Prince', 'F', '1966-04-17', '321-879-4545', DATETIME('now'), DATETIME('now')
")
答案 0 :(得分:2)
当您向其中插入任何内容或NULL时,自动增量列会获得自动递增的值。
将ID列设置为NULL:
INSERT INTO students
SELECT NULL, 'somebody', 'z'
...
或指定部分列,不包含ID列:
INSERT INTO students(name, gender)
SELECT 'somebody', 'z'
...
答案 1 :(得分:1)
您使用ruby标记了您的问题,因此使用续集(*)的解决方案可能会对您有所帮助:
(*)备注:续集在后台加载sqlite3。
require 'sequel'
DB = Sequel.sqlite
DB.create_table(:tab1){
primary_key :id
field :a, :type => :nvarchar, :size => 10
field :b, :type => :nvarchar, :size => 10
}
DB[:tab1].multi_insert([
{ :a => 'a1', :b => 'b1'},
{ :a => 'a2', :b => 'b2'},
{ :a => 'a3', :b => 'b3'},
])
puts DB[:tab1].all
输出:
{:id=>1, :a=>"a1", :b=>"b1"}
{:id=>2, :a=>"a2", :b=>"b2"}
{:id=>3, :a=>"a3", :b=>"b3"}
如果您更喜欢原始SQL,可以使用:
require 'sequel'
DB = Sequel.sqlite
DB.create_table(:students){
primary_key :id
field :first_name, :type => :nvarchar, :size => 10
field :last_name, :type => :nvarchar, :size => 10
field :gender, :type => :nvarchar, :size => 1
field :birthday, :type => :date
field :phone, :type => :nvarchar, :size => 10
field :created_at, :type => :date
field :updated_at, :type => :date
}
DB.execute("
INSERT INTO 'students'
('first_name', 'last_name', 'gender', 'birthday', 'phone', 'created_at', 'updated_at')
VALUES
('Brett', 'Iton', 'M', '1966-01-17', '415-879-54451', DATETIME('now'), DATETIME('now')),
('Lady','Gaga', 'F', '1970-03-17', '213-879-4545', DATETIME('now'), DATETIME('now')),
('Former','Prince', 'F', '1966-04-17', '321-879-4545', DATETIME('now'), DATETIME('now'))
")
puts DB[:students].all
请注意:一个VALUES子句中的最大行数为1000 - 但我认为这对您没有问题。