在 MySQL 预处理语句中使用具有表名的用户定义变量?
我们先创建一个表 -
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) ); Query OK, 0 rows affected (0.71 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable(StudentName) values('Chris'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(StudentName) values('David'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable(StudentName) values('Sam'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(StudentName) values('Mike'); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable;
这将产生以下输出 -
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | David | | 3 | Sam | | 4 | Mike | +-----------+-------------+ 4 rows in set (0.00 sec)
以下是如何使用用户定义变量设置表名并使用 MySQL 预处理语句的方法 -
mysql> set @tableName = 'DemoTable'; Query OK, 0 rows affected (0.04 sec) mysql> set @queryToSelectStudentName := concat('select StudentName from ',@tableName); Query OK, 0 rows affected (0.28 sec) mysql> prepare executeQuery from @queryToSelectStudentName; Query OK, 0 rows affected (0.04 sec) Statement prepared mysql> execute executeQuery;
这将产生以下输出 -
+-------------+ | StudentName | +-------------+ | Chris | | David | | Sam | | Mike | +-------------+ 4 rows in set (0.00 sec)
广告