SQL中占位符?的用法介绍~

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就构造好了。

若要创建每次使用不同值的查询,可以在查询中使用参数。参数是在运行查询时所提供值的占位符。

带参数的 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("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 张三  

最终个人理解,占位符就字面意思(即占位用的),通过传入参数或设定参数取代所占用的位置,完成字符串的拼接~

猜你喜欢

转载自blog.csdn.net/litrainy/article/details/84067808