我有一张 table
CREATE TABLE `category` (
`category_id` int(11) ,
`T1` varchar(50) DEFAULT NULL,
`T2` varchar(50) DEFAULT NULL,
`T3` varchar(50) DEFAULT NULL,
`T4` varchar(50) DEFAULT NULL,
`T5` varchar(50) DEFAULT NULL
)
mysql> select * from category;
+-------------+----------+-------------+---------------+------+------+
| category_id | T1 | T2 | T3 | T4 | T5 |
+-------------+----------+-------------+---------------+------+------+
| 145 | Pop Corn | Regular Tub | Plain Salted | NULL | NULL |
| 150 | Pop Corn | Buckets | Plain Salted | NULL | NULL |
| 151 | Pop Corn | Jumbo | Plain Salted | NULL | NULL |
| 152 | Pop Corn | Regular Tub | Butter Scotch | NULL | NULL |
| 153 | Pop Corn | Regular Tub | Tomoto Tango | NULL | NULL |
| 154 | Pop Corn | Buckets | Butter Scotch | NULL | NULL |
| 222 | Pop Corn | NULL | NULL | NULL | NULL |
| +-------------+----------+-------------+---------------+------+-----
当我运行下面的程序时,它会在表中插入一条新记录,如下所示
223 Pop Corn | Buckets | NULL | NULL | NULL
它实际上应该更新 category_id 222 的行,因为爆米花已经存在了
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args)
{
String inputrequest = "Pop Corn@Buckets";
String values[] = inputrequest.split("@");
String sqlselect = "";
Connection dbConnection = null;
PreparedStatement selectpst = null;
ResultSet resultset = null;
PreparedStatement selectpst2 = null;
ResultSet resultset2 = null;
String sqlselect2 = "";
Statement updateStatement = null;
// Length == 2
if(values.length==2)
{
sqlselect = "select category_id from category where T1 = ? AND T2 = ? AND T3 IS NULL"
selectpst = dbConnection.prepareStatement(sqlselect);
selectpst.setString(1, values[0]);
selectpst.setString(2, values[0]);
resultset = selectpst.executeQuery();
if(resultset.next())
{
System.out.println("Already exists");
}
else
{
sql = "Insert into category (T1,T2,T3,T4,T5) values ('"+values[0]+"','"+values[1]+"',NULL,NULL,NULL) ";
updateStatement.executeUpdate(sql);
}
}
}
}
谁能帮我解决这个问题??
最佳答案
你的参数设置错误:
selectpst.setString(1, values[0]);
selectpst.setString(2, values[0]);
我认为应该是:
selectpst.setString(1, values[0]);
selectpst.setString(2, values[1]);
关于java - 在这种情况下如何插入或更新数据库行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27379787/