带参数的MySql插入

时间:2016-05-06 09:01:46

标签: mysql

set @id = 1
insert into table (col1, col2, col3)
values (@id, 'x', 2)

set @id = 1
insert into table (col1, col2, col3)
select @id, 'x', 2

两者都失败了。

我哪里错了?

2 个答案:

答案 0 :(得分:3)

您应该在句子之间添加;

set @id = 1;
insert into table (col1, col2, col3)
values (@id, 'x', 2)

或者

set @id = 1;
insert into table (col1, col2, col3)
select @id, 'x', 2

见这里:

SQL Fiddle

MySQL 5.6架构

CREATE TABLE TEST (COL1 CHAR(10),COL2 CHAR(10),COL3 CHAR(10));
set @id = 1;
insert into TEST (col1, col2, col3)
select @id, 'x', 2;
set @id = 1;
insert into TEST (col1, col2, col3)
values (@id, 'x', 2);

查询1

SELECT * FROM TEST

<强> Results

| COL1 | COL2 | COL3 |
|------|------|------|
|    1 |    x |    2 |
|    1 |    x |    2 |

答案 1 :(得分:2)

在每次查询后添加;并在``中获取表名 table是保留关键字

set @id = 1;
insert into `table` (col1, col2, col3) values (@id, 'x', 2);