mysql语句占位符_sql语句中的占位符?有什么作⽤
String sql = "SELECT urid,name FROM tur WHERE urid=? AND password=?" ;
pstmt = conn.prepareStatement(sql) ;
pstmt.tString(1,urid) ; // 这⾥设置了第⼀个?的值
pstmt.tString(2,password) ; // 这⾥设置了第⼆个?的值 等你“tString”完所有的?后,你的sql就构造好了。
若要创建每次使⽤不同值的查询,可以在查询中使⽤参数。参数是在运⾏查询时所提供值的占位符。带参数的 SQL 语句可能如下所⽰,其中“?”表⽰代表作者 ID 的参数:
SELECT title_id
FROM titleauthor
WHERE (au_id = ?)
可使⽤参数的位置可以将参数⽤作⽂本值(⽂本值或数值)的占位符。最常见的是,参数经常在单个⾏或
组的搜索条件中(即在 SQL 语句的WHERE 或 HAVING ⼦句中)⽤作占位符。 某些数据库允许在表达式中将参数⽤作占位符。
使⽤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("sql.jdbc.Driver");
//使⽤驱动创建连接
Connection("jdbc:mysql://localhost:3306/mysql","root","111111");
//定义sql语句
String sql="inrt into hehe values(?,?,?)";
//创建执⾏命令对象
ps= con.prepareStatement(sql);
/
/设置参数
ps.tInt(1, 1);
ps.tString(2,_name);
ps.tString(3, _gender);
//执⾏命令并接受结果
int uteUpdate();
System.out.println(result);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(null!=ps)
ps.clo();
if(null!=con)
con.clo();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.得到结果
ID
name
gender
1
张三
男
最终个⼈理解,占位符就是字⾯意思,占位⽤的,传⼊参数便会代替这个位置