字符串变量作为mysql的查询条件的解决方法

最近在写地铁查询系统的时候,遇到了一个问题

线路查询:要求输入任意一个站点名,要求能查询出该站点所在的线路

这就肯定用到sql语句中的"select * from table where station="+输入的站点变量

二我们的sql语句中,一般的查询是以int型为查询条件

比如"select * from table where id="+id;

而在查询中,如果要查询字符串变量的话,就得打成这样"select * from table where station="+"苹果园"

可是如果苹果园是个station变量呢?反正不能在""中间夹带station吧?

那样只能查询一次,就是station=station,以后再次查询的结果永远是苹果园

别问我怎么知道的,肯定是这样错过啦才发现的

-------------------------------------------------------------------------------------------------------------------

最新发现的解决方法来了

  public static int search_line(String station){
      int line =1;
        try {
            Connection conn = util.getConnection();
            Statement state = null;
            String sql="select * from buke where station=?";
            PreparedStatement  pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,station);
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()){

                line= Integer.parseInt((rs.getString("line")));

            }
            rs.close();
            pstmt.close();
            conn.close();
        }
        catch(SQLException e) {

            e.printStackTrace();
        }
        return line;

    }

注意观察中间的这一句

 PreparedStatement  pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,station);

上网搜索了一下,大概意思是给sql语句中的第一个问号赋值station

这也就意味着可以有第二个问号,第三个问号,以后再摸索吧

 

&end

 

posted @ 2022-04-02 22:59  zrswheart  阅读(205)  评论(0编辑  收藏  举报