在 MySQL 预处理语句中使用变量
让我们先创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.53 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable(FirstName,LastName) values('John','Smith'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(FirstName,LastName) values('David','Miller'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(FirstName,LastName) values('John','Doe'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(FirstName,LastName) values('Chris','Brown'); Query OK, 1 row affected (0.15 sec)
使用 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 中的预处理语句设置变量的查询 −
mysql> set @yourTableName :='DemoTable'; Query OK, 0 rows affected (0.00 sec) mysql> set @query :=CONCAT('select `LastName` from ',@yourTableName, ' where Id=3 '); Query OK, 0 rows affected (0.00 sec) mysql> prepare myStatement from @query; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> execute myStatement;
这将产生以下输出 −
+----------+ | LastName | +----------+ | Doe | +----------+ 1 row in set (0.00 sec)
广告