0

我从表单中插入值时收到错误消息。错误是Column count 与 raw 1 的 value count 不匹配。我的第 5 个字符串值必须存储为sql 中的日期数据类型。

String s1=this.txtUsername.getText();
String s2=this.txtPassword.getText();
String s3=this.txtName.getText();
String s4=this.txtAddress.getText();
String s5=this.txtContractEndDetails.getText();


         connection getcon = new connection();
         Connection conn;


    try{
        conn=getcon.creatConnection();
        Statement stmt=conn.createStatement();

        stmt.executeUpdate("insert into TravelGuide(username,password,name,address,contract_end_date)values ('"+s1+"','"+s2+"','"+s3+"','"+s4+"'+'"+s5+"')");



        }
    catch(Exception ex){
        JOptionPane.showMessageDialog(PanelTG, ex.getMessage(),"Error Occured",2);
    }

这是我用于 SQL 查询的相关表。

  create table TravelGuide(
  username char(20),
  password char(20),
  name varchar(100),
  address varchar(150),
  contract_end_date date,
  constraint TravelGuide_PK primary key(username)
  );

已编辑

我很困惑

preparedStatement("insert into TravelGuide (username,password,name,address,contract_end_date) values (?, ?, ?, ?, ?)");

你能解释一下吗?

这是正确的吗?** 标记内的代码给出错误非法表达式开头并且找不到符号..请帮助我..

try {
    conn=getcon.creatConnection();

    **String sql="insert into TravelGuide("+"username,"+"password,,"+,"name,"+"address,"+"contract_end_date)"+"values(?,?,?,?,?)";**
    PreparedStatement stmt = conn.**preparedStatement**(sql);
    java.sql.Date dtValue = java.sql.Date.valueOf(s5); 

    stmt.setString(1, s1);
    stmt.setString(2, s2);
    stmt.setString(3, s3);
    stmt.setString(4, s4);
    stmt.setDate(5, dtValue);
    stmt.executeUpdate();                
}
4

2 回答 2

4

在 中try,改为执行以下操作:

conn = getconn.creatConnection();
PreparedStatement stmt = conn.prepareStatement("insert into TravelGuide (username,password,name,address,contract_end_date) values (?, ?, ?, ?, ?)");

java.sql.Date date = someFunctionToConvertYourDateStringToADate(s5);

stmt.setString(1, s1);
stmt.setString(2, s2);
stmt.setString(3, s3);
stmt.setString(4, s4);
stmt.setDate(5, date);
stmt.executeUpdate();

[and so on]

这样,您就可以免受 SQL 注入攻击,而且您不必担心如何将字符串转换为特定数据库对date列所需的格式。java.sql.Date给定一个对象,JDBC 驱动程序将为您处理。

于 2012-04-11T03:19:07.320 回答
0
stmt.executeUpdate("insert into TravelGuide(username,password,name,address,contract_end_date)values ('"+s1+"','"+s2+"','"+s3+"','"+s4+"'**+**'"+s5+"')");

为什么+,我想我应该是,

于 2012-04-11T03:25:34.070 回答