如果record是现有Update,或者根据相应的条目插入新记录

时间:2014-12-09 14:59:31

标签: java

我有一张桌子

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 |
| +-------------+----------+-------------+---------------+------+-----

我的逻辑

String reqstr="Pop Corn@Small@Test";
String values[] = reqstr.split("@");

            else  if(values.length==3)
            {

                sqlselect = "select category_id from category where T1 = ? AND T2 IS NULL AND T3 IS NULL AND T4 IS NULL"  ;
                    selectpst = dbConnection.prepareStatement(sqlselect);
                    selectpst.setString(1, values[0]);
                    resultset = selectpst.executeQuery();
                    if(resultset.next())
                    {
                            sql = "update category set T3 = '"+values[2]+"' T2 = '"+values[1]+"' where T1 ='"+values[0]+"'   
                            updateStatement.executeUpdate(sql);     

// similarly check for T2 , T3 , T4 also 

                    }

                    else
                    {

                    // Insert logic here 

                    }



            }

可以修改这个逻辑以提高效率吗?

我面临的问题是,例如在这种情况下,Pop Corn已经存在,它应该更新那个,否则它应该插入新的

同样,如果Pop Corn Small存在,它应该更新那个或者插入新记录

0 个答案:

没有答案