简体   繁体   English

MySQL 准备语句 - ? 在 WHERE 子句中

[英]MySQL prepare statement - ? in WHERE clause

This is a silly simple thing but I failed to google out an answer:这是一件愚蠢而简单的事情,但我没有在谷歌上找到答案:

 PREPARE stmt1 FROM 'SELECT productCode, productName

                 FROM products

                 WHERE productCode = ?';

What is the ?是什么 ? at the end?在末尾? '?' '? is not a wildcard in SQL so what is it...不是 SQL 中的通配符,那么它是什么......

-- Edit: thank you! -- 编辑:谢谢!

? is called a parameter placeholder.称为参数占位符。

The statement may not be complete, because data values that are unknown at preparation time are represented by the question mark characters that serve as parameter markers.该语句可能不完整,因为在准备时未知的数据值由用作参数标记的问号字符表示。 At the time the statement is executed, you provide specific data values, one for each parameter in the statement.在执行语句时,您提供特定的数据值,语句中的每个参数一个。

Are you using an ORM such as Doctrine?你在使用像 Doctrine 这样的 ORM 吗? ORMs usually put placeholders (?) in place of values and only apply them before execution. ORM 通常用占位符 (?) 代替值,并且只在执行前应用它们。

? is used as a placeholder for the values that are not known in advance.用作事先未知的值的占位符。

Suppose that you have two ?假设你有两个? in your statement, then you can define what parameter what values will be in place of them by assigning them the values using the index of ?在您的语句中,然后您可以通过使用? (as we do in java) (就像我们在 Java 中所做的那样)

I am using an example of Java to make you understand PreparedStatement :我正在使用 Java 的一个例子来让你理解 PreparedStatement :

Let say my query is :假设我的查询是:

PreparedStatement ps = connection.prepareStatement(
                    `select * from employee where ename = ? and location = ?`);

So I have defined the placeholder for the values to be checked against ename and location while executing the query.因此,我在执行查询时为要根据enamelocation进行检查的值定义了占位符。

Now I set the values without changing my query (as we in java)现在我在不更改查询的情况下设置值(就像我们在 Java 中一样)

ps.setString(1,"John");
ps.setString(2,"New York");

So now the query at run time will be :所以现在运行时的查询将是:

select * from employee where ename = 'John' and location = 'New York'

And next time if I want to change the values then I will do :下次如果我想更改这些值,那么我会这样做:

ps.setString(1,"Williams");
ps.setString(2,"London");

So now my query will be :所以现在我的查询将是:

select * from employee where ename = 'Williams' and location = 'London'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM