在MySQL准备语句中使用变量
让我们首先创建一个表-
mysql> create table DemoTable(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(20),
LastName varchar(20)
);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(FirstName,LastName) values('John','Smith');mysql> insert into DemoTable(FirstName,LastName) values('David','Miller');
mysql> insert into DemoTable(FirstName,LastName) values('John','Doe');
mysql> insert into DemoTable(FirstName,LastName) values('Chris','Brown');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-----------+----------+| Id | FirstName | LastName |
+----+-----------+----------+
| 1 | John | Smith |
| 2 | David | Miller |
| 3 | John | Doe |
| 4 | Chris | Brown |
+----+-----------+----------+
4 rows in set (0.00 sec)
以下是在MySQL中使用prepare语句时设置变量的查询-
mysql> set @yourTableName :='DemoTable';mysql> set @query :=CONCAT('select `LastName` from ',@yourTableName, ' where Id=3 ');
mysql> prepare myStatement from @query;
Statement prepared
mysql> execute myStatement;
这将产生以下输出-
+----------+| LastName |
+----------+
| Doe |
+----------+
1 row in set (0.00 sec)
以上是 在MySQL准备语句中使用变量 的全部内容, 来源链接: utcz.com/z/348868.html