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
最終個人理解,占位符就是字面意思,占位用的,傳入參數便會代替這個位置