Unable to Create Prepared Statements in MySQL

2019-08-24 12:12发布

问题:

I'm trying to create a prepared statement in MySQL that takes in a single parameter. When I try this on the command line I get a syntax error. However, when there are no variables in my prepared statement, I am able to create them fine. Below is a copy and paste of what I am seeing at the MySQL command prompt:

mysql> PREPARE state_name FROM "select * from ? limit 1";

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? limit 1' at line 1

mysql> PREPARE state_name FROM "select * from documents limit 1";
Query OK, 0 rows affected (0.00 sec)
Statement prepared

The version of MySQL I'm using is 5.0.77-log.

Is there a syntax error I'm not seeing? And are there any config parameters I have to set in order to get prepared statements to work?

回答1:

You can't pass in table names as prepared statement parameters, I'm afraid, neither can you pass columns to group or sort by. The only thing you can parametrize are fields in where clauses or for updates:

PREPARE state_name FROM "select * from documents where id = ?";

PREPARE state_name FROM "update documents set field = ? where id = ?";


回答2:

If you want to create a single prepare statement and use it for more than one table, you cand actually create a variable for every table, and then create the statement using this variable, as the MySQL manual explain it :

mysql> USE test;
mysql> CREATE TABLE t1 (a INT NOT NULL);
mysql> INSERT INTO t1 VALUES (4), (8), (11), (32), (80);

mysql> SET @table = 't1';
mysql> SET @s = CONCAT('SELECT * FROM ', @table);

mysql> PREPARE stmt3 FROM @s;
mysql> EXECUTE stmt3;
+----+
| a  |
+----+
|  4 |
|  8 |
| 11 |
| 32 |
| 80 |
+----+

mysql> DEALLOCATE PREPARE stmt3;