我正在尝试阻止SQL注入,并且我已经转换了这个原始插入查询:
stmt = conn.createStatement();
String sql = "insert into customer (cust_id, cust_name, father_name, birth_date, CNIC, city, card_num, acc_num, bank_name, address, email, ph_num) values ( " + String.valueOf(txtcust_id.getText()) + ",'" + txtcust_name.getText()
+ "','" + txtf_name.getText() + "','" + txtb_date.getText() + "','" + txtcnic.getText() + "','" + txtcity.getText() + "','" + txtcard_num.getText() + "','" + txtacc_num.getText() + "','" + txtb_n.getText() + "','" + txtadd.getText() + "','" + txtemail.getText()+ "','" + txtph_num.getText() + "' )";
//stmt.executeUpdate(sql);
int rowsAffected = stmt.executeUpdate(sql);
String msg = "Insert Query Execution Failed"; if(rowsAffected > 0){ JOptionPane.showMessageDialog(null, "Query Successful"); }
else {
JOptionPane.showMessageDialog(this, msg, "Execution Alert", JOptionPane.INFORMATION_MESSAGE);
}
我已将其转换为参数化查询,如下所示:
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "insert into customer (cust_id, cust_name, father_name, birth_date, CNIC, city, card_num, acc_num, bank_name, address, email, ph_num) values (?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, Integer.parseInt(txtcust_id1.getText()));
stmt.setString(2, txtcust_name1.getText());
stmt.setString(3, txtf_name1.getText());
stmt.setDate(4, sqlDateDOB);
stmt.setLong(5, Integer.parseInt(txtcnic1.getText()));
stmt.setString(6, txtcity1.getText() );
stmt.setLong(7, Integer.parseInt(txtcard_num1.getText()));
stmt.setLong(8, Integer.parseInt(txtacc_num1.getText()));
stmt.setString(9, txtb_n1.getText());
stmt.setString(11, txtadd1.getText());
stmt.setString(12, txtemail1.getText());
stmt.setInt(13, Integer.parseInt(txtph_num1.getText()));
//stmt.executeUpdate(sql);
int rows = stmt.executeUpdate(sql);
String msg = "Insert Query Execution Failed";
if(rows > 0) {
msg = "Insert Query Executed Successfully";
}
JOptionPane.showMessageDialog(this, msg, "Execution Alert", JOptionPane.INFORMATION_MESSAGE);
我遇到的问题是setDate
。我的数据格式为yyyy,mm,dd
。 sqlDateDOB
变量的定义如下:
String str = txtb_date.getText(); //must not be empty text!
SimpleDateFormat fmt = new SimpleDateFormat("yyyy,MM,dd");
java.sql.Date sqlDateDOB = new java.sql.Date(fmt.parse(str).getTime());