sql语句中的占位符?有什么作用

String sql = "SELECT userid,name FROM tuser WHERE userid=? AND password=?" ;

pstmt = conn.prepareStatement(sql) ;

pstmt.setString(1,userid) ; // 这里设置了第一个?的值

pstmt.setString(2,password) ; // 这里设置了第二个?的值 等你“setString”完所有的?后,你的sql就构造好了。

--------------------- 本文来自 feidegenggao1 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/feidegenggao1/article/details/6243961

若要创建每次使用不同值的查询,可以在查询中使用参数。参数是在运行查询时所提供值的占位符。带参数的 SQL 语句可能如下所示,其中“?”表示代表作者 ID 的参数:

SELECT title_id

FROM titleauthor

WHERE (au_id = ?)

可使用参数的位置可以将参数用作文本值(文本值或数值)的占位符。最常见的是,参数经常在单个行或组的搜索条件中(即在 SQL 语句的 WHERE 或 HAVING 子句中)用作占位符。 某些数据库允许在表达式中将参数用作占位符。

--------------------- 本文来自 limengmeng9006 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/limengmeng9006/article/details/8200538

使用PreparedStatement执行SQL语句时占位符(?)的用法

1.Student数据库表

ID  name gender
     

 

 

 

 

 

2.Java代码

public static void main(String[] args) {
int _id=1;
String _name="张三";
String _gender="男";
Connection con=null;
PreparedStatement ps=null;

try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//使用驱动创建连接
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","111111");
//定义sql语句
String sql="insert into hehe values(?,?,?)";
//创建执行命令对象
ps= con.prepareStatement(sql);
//设置参数
ps.setInt(1, 1);
ps.setString(2,_name);
ps.setString(3, _gender);

//执行命令并接受结果
int result=ps.executeUpdate();
System.out.println(result);

} catch (ClassNotFoundException e) {

e.printStackTrace();
} catch (SQLException e) {

e.printStackTrace();
}finally{
try {
if(null!=ps)
ps.close();
if(null!=con)
con.close();
} catch (SQLException e) {

e.printStackTrace();
}
}

}

}

3.得到结果

 

ID name gender
1 张三

 

 

 

 

 

 

--------------------- 本文来自long_street_to_walk 博客 ,全文地址请点击:https://www.cnblogs.com/wffj150926/p/6141241.html

 

最终个人理解,占位符就是字面意思,占位用的,传入参数便会代替这个位置

posted on 2018-09-22 12:15  songsong_p_blue  阅读(15667)  评论(0编辑  收藏  举报