java中string a="10"
String sql="select * from temp where id ="+a; vc中:
sql.format("select * from temp where id= %s",a)我觉的在java中用“+”操作符号去配凑SQL语句在变量多的时候比较容易乱结构也不清晰,大家有没有什么好的方法呢?或者可以想VC一样 java 也能有Format函数

解决方案 »

  1.   

    使用PrepareStatement啊strSQL = "select * from temp where id =?";
          
    prepare = con.prepareStatement(strSQL);
    prepare.setString(1,a); 
      

  2.   

    有,用prepareStatement
    如:ps = con.prepareStatement("select * from table where name=?");
        ps.setString(1,"zhangsan");
    其中的1代表第一个问号,后面是它的值,以此类推。
      

  3.   

    如果是insert into 类的语句也行吗? 应该如何写?
      

  4.   

    如果有很多的检索条件,或很多的更新条件,除了使用上面的方法
    一定要使用StringBuffer,例如:
    StringBuffer sbsql = new StringBuffer();
    sbsql.append("select * from table where name=");
    sbsql.append(qryName);
    sbsql.append(" and password=");
    sbsql.append(aryPwd);
    pstmt=conn.prepareStatement(sbsql.toString());
      

  5.   

    StringBuffer是自增长的
    String在连接的时候,会生成原来String的copy然后连接
    再new新的String对象,效率很低,不提倡使用
      

  6.   

    strSQL = "insert into person(ID,EntID,Nam,Des) VALUES  (?,?,?,?)";
          
    prepare = con.prepareStatement(strSQL);
    prepare.setString(1,(ProcEntID)); 
    prepare.setInt(2,(ProdEntID)); 
    prepare.setString(3,(BrdNam)); 
    prepare.setString(4,(BrdDes));
      

  7.   

    当然可以:
      ps = con.prepareStatement("insert into mytable values(?,?)");
      ps.setInt(1);
      ps.setName("Jack");
      ps.executeUpdate();