准备语句参数" SELECT ... WHERE para1或para2" , 怎么样?

时间:2018-02-21 07:11:34

标签: java sql prepared-statement

有人可以解释正确的方法吗?当使用(WHERE)" OR"?

时,我们如何传递参数?
"SELECT ... WHERE paraX=? OR paraY=?";

我尝试使用以下代码,但它们不会执行。

pstm.setString(1, 1st_para);
pstm.setString(2, 2nd_para);

(请注意我是JAVA和Preparedstatement的初学者)

感谢名单!

2 个答案:

答案 0 :(得分:3)

作为Java初学者,请查看以下代码:DB表:

CREATE TABLE `employee` (
  `emp_id` INT NOT NULL AUTO_INCREMENT,
  `emp_name` VARCHAR(45) NOT NULL,
  `salary` DECIMAL NULL,
  `age` INT NULL,
  PRIMARY KEY (`emp_id`));

INSERT INTO `employee` (`emp_name`, `salary`, `age`) VALUES ('Abc', '100.23', '23');
INSERT INTO `employee` (`emp_name`, `salary`, `age`) VALUES ('Def', '220.2', '34');
INSERT INTO `employee` (`emp_name`, `salary`, `age`) VALUES ('Pqr', '50.44', '12');
INSERT INTO `employee` (`emp_name`, `salary`, `age`) VALUES ('Xyz', '75.66', '20');
INSERT INTO `employee` (`emp_name`, `salary`, `age`) VALUES ('Lmn', '150.0', '30');

获取mysql-connector-java依赖关系(使用Maven,或将其包含在classpath中)。基本代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PreparedStatementDemo {
  public static void main(String[] args) {
    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
      System.err.println("No driver found..");
    }

    try {
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://${host}:${port}/${dbname}", "${username}", "${password}");

      PreparedStatement prepareStatement =
          conn.prepareStatement("SELECT * FROM employee WHERE salary > ? AND age > ?");
      prepareStatement.setDouble(1, 75.0);
      prepareStatement.setInt(2, 20);

      ResultSet resultSet = prepareStatement.executeQuery();

      int i = 1;
      while (resultSet.next()) {
        System.out.println("Row: " + i);
        System.out.println("\tId: " + resultSet.getInt(1));
        System.out.println("\tName: " + resultSet.getString(2));
        System.out.println("\tSalary: " + resultSet.getDouble(3));
        System.out.println("\tAge: " + resultSet.getInt(4));
        i++;
      }

      prepareStatement.close();
      conn.close();
    } catch (SQLException e) {
      System.err.println("Error in DB communication: " + e.getMessage());
    }
  }
}

编辑连接字符串的值。 PreparedStatement接受索引从1开始的运行时值。 ResultSet也是如此。

答案 1 :(得分:0)

"SELECT ... WHERE paraX=? OR paraY=?";
pstm.setString(1, "1st_Text");
pstm.setString(2, "2nd_Text");

我发现了问题,我的编码错误发生了错误。 '因为我在TextArea的ActionForforme中调用了该方法。但必须在KeyReleased Area中调用它。所以,代码是正确的。为什么我之前没有提到过代码,'因为这只是一种方法,但我还没有完成编码..

感谢所有宝贵的时间,你浪费了我的问题..

public static void FillAttendsTable(JTable table, String valueToSearch) throws Exception {

    clasid = jTextField_Class_ID.getText();
    studid = jTextField_Stud_ID.getText();

    if((!clasid.equals("") && studid.equals("")) || (clasid.equals("") && !studid.equals(""))){

        cs = " AND (cs.clas_id = ? OR cs.stud_id = ?)";

    }else if(!clasid.equals("") && !studid.equals("")){

        cs = " AND cs.clas_id = ? AND s.stud_id = ?";

    }else if(clasid.equals("") && studid.equals("")){

        cs = " AND CONCAT(c.clas_gred,clas_stat,clas_end,c.note,stud_fnem)LIKE ?";
    }

    Connection conc = Config.DBConnector.getConnection();

    if(jCheckBox_Present.isSelected() && (!clasid.equals("") || !studid.equals(""))){
        qri = "SELECT DISTINCT cs.clas_id,c.clas_gred,s.stud_id,stud_fnem,stud_lnem,a.atn_date,clas_stat,clas_end FROM (((tbl_clas_stud AS cs JOIN tbl_student As s ON cs.stud_id = s.stud_id) JOIN tbl_class AS c ON cs.clas_id = c.clas_id) JOIN tbl_attends AS a ON a.clas_id=cs.clas_id) WHERE NOT EXISTS (SELECT a.stud_id FROM tbl_attends AS a WHERE cs.stud_id=a.stud_id)"+cs;
    num = "1";

    pstm = (PreparedStatement) conc.prepareStatement(qri);
    pstm.setString(1, clasid);
    pstm.setString(2, studid);

    }else if(jCheckBox_Absent.isSelected() && (!clasid.equals("") || !studid.equals(""))){
        qri = "SELECT DISTINCT cs.clas_id,c.clas_gred,s.stud_id,stud_fnem,stud_lnem,a.atn_date,clas_stat,clas_end FROM (((tbl_clas_stud AS cs JOIN tbl_student As s ON cs.stud_id = s.stud_id) JOIN tbl_class AS c ON cs.clas_id = c.clas_id) JOIN tbl_attends AS a ON a.clas_id=cs.clas_id) WHERE EXISTS (SELECT a.stud_id FROM tbl_attends AS a WHERE cs.stud_id=a.stud_id)"+cs;
    num = "0";

    pstm = (PreparedStatement) conc.prepareStatement(qri);
    pstm.setString(1, clasid);
    pstm.setString(2, studid);

    }else if(jCheckBox_Absent.isSelected()) {
        qri = "SELECT DISTINCT cs.clas_id,c.clas_gred,s.stud_id,stud_fnem,stud_lnem,a.atn_date,clas_stat,clas_end FROM (((tbl_clas_stud AS cs JOIN tbl_student As s ON cs.stud_id = s.stud_id) JOIN tbl_class AS c ON cs.clas_id = c.clas_id) JOIN tbl_attends AS a ON a.clas_id=cs.clas_id) WHERE EXISTS (SELECT a.stud_id FROM tbl_attends AS a WHERE cs.stud_id=a.stud_id)"+cs; 
    num = "0";

    pstm = (PreparedStatement) conc.prepareStatement(qri);
    pstm.setString(1, "%" + valueToSearch + "%");

    }else if(jCheckBox_Present.isSelected()) {
        qri = "SELECT DISTINCT cs.clas_id,c.clas_gred,s.stud_id,stud_fnem,stud_lnem,a.atn_date,clas_stat,clas_end FROM (((tbl_clas_stud AS cs JOIN tbl_student As s ON cs.stud_id = s.stud_id) JOIN tbl_class AS c ON cs.clas_id = c.clas_id) JOIN tbl_attends AS a ON a.clas_id=cs.clas_id) WHERE NOT EXISTS (SELECT a.stud_id FROM tbl_attends AS a WHERE cs.stud_id=a.stud_id)"+cs;
    num = "1";

    pstm = (PreparedStatement) conc.prepareStatement(qri);
    pstm.setString(1, "%" + valueToSearch + "%");

    }

    ResultSet rs = pstm.executeQuery();
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    dtm.setRowCount(0);

    Object[] row;

    while (rs.next()) {
        row = new Object[9];
        row[0] = rs.getString(1);
        row[1] = rs.getString(2);
        row[2] = rs.getString(3);
        row[3] = rs.getString(4);
        row[4] = rs.getString(5);
        row[5] = rs.getString(6);
        row[6] = rs.getString(7);
        row[7] = rs.getString(8);
        row[8] = num;

        dtm.addRow(row);
    }
}