从表单插入值时收到错误消息。 错误列数与原始1的值计数不匹配。 我的第5个字符串值必须在sql中存储为 date 数据类型。
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();
}
答案 0 :(得分: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驱动程序将为您处理。
答案 1 :(得分:0)
stmt.executeUpdate("insert into TravelGuide(username,password,name,address,contract_end_date)values ('"+s1+"','"+s2+"','"+s3+"','"+s4+"'**+**'"+s5+"')");
为什么+,我想我应该是,