简体   繁体   English

在SQL查询中使用时,“=?”表示什么

[英]What does “=?” represent when used in an SQL query

I'm fairly new to SQL and I'm currently reworking a java program that another programmer has developed. 我是SQL的新手,我正在重新编写另一个程序员开发的java程序。 When I print one of his query select statements the script contains sql syntax: 当我打印他的一个查询select语句时,脚本包含sql语法:

SELECT * from database WHERE id = ?

I just want know what =? 我只想知道什么=? is supposed to do? 应该怎么做? I've been googling around and I can't find any relevant answer. 我一直在谷歌搜索,我找不到任何相关的答案。

It's not a SQL notation, but a JDBC (Java Database Connectivity) notation. 它不是SQL表示法,而是JDBC(Java数据库连接)表示法。 The ? ? gets replaced with a parameter that is specified separately. 被替换为单独指定的参数。 Using this approach, instead of trying to substitute the parameter yourself into the string, helps prevent the risk of SQL injection . 使用此方法,而不是尝试将参数替换为字符串,有助于防止SQL注入的风险。

The ? ? is a place holder, a parameter, so that you can pass it in dynamically and return different results for different parameters. 是一个占位符,一个参数,以便您可以动态传递它并为不同的参数返回不同的结果。

Somewhere in the code you should see that he adds the parameter to the Statement object and execute it. 在代码中的某处,您应该看到他将参数添加到Statement对象并执行它。

Most likely you are using a tool that will replace the "?" 很可能你使用的工具将取代“?” with an actual value. 具有实际价值。 I've seen this in other tools before such as SQL DTS (Data Transformation Services)... but that's showing how old I am :) 我之前在其他工具中看到过这种情况,例如SQL DTS(数据转换服务)......但是这显示我多大了:)

The ? ? is not part of the SQL language. 不是SQL语言的一部分。

The ? ? is a place holder used in SQL queries when used with JDBC Prepared statement . 是与JDBC Prepared语句一起使用时在SQL查询中使用的占位符。 Using a prepared statement has advantages over the normal statement specially when you use it repeatedly (say in a loop). 使用预准备语句优于正常语句,特别是当您重复使用它时(例如在循环中)。

Here is an example : 这是一个例子:

PreparedStatement ps = 
    connection.prepareStatement("select name from users where user_name = ?");
ps.setString(1, "user1");

the "?" “?” gets replace by "user1" when the query is run and the first name of the user with user name "user1" is returned. 运行查询时将替换为“user1”,并返回用户名为“user1”的用户的名字。

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

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