Corona SQLIte:检查值是否存在

时间:2014-11-22 13:36:19

标签: sqlite lua corona

我想检查我的SQL请求是否可以返回值:

Search_IDItem = "SELECT * FROM giftshop WHERE id ="..item_id..""
            for row_2 in db:nrows(Search_IDItem) do (..)

CheckInventory = "SELECT * FROM inventory WHERE code ="..row_2.code..""
if CheckInventory ~= nil then
    print(row_2.code)
    updateItemsCode(row_2.code, "inventory", "qtyoninventory", row_2.qtyoninventory+1)
else
    insertInventory(2,row_2.code, row_2.name, row_2.src, row_2.desc, "no",row_2.qtyoninventory,row_2.price,row_2.usetxt)
end

错误是:

  

near“=”:语法错误

基本上,我想知道价值是否存在,我只会更新字段“数量”,如果没有,我会创建新项目。

不幸的是,它不起作用!有什么建议或解决方案吗?

2 个答案:

答案 0 :(得分:1)

语法错误是SQL对您的查询产生误解的结果 最常见的原因之一是不正确的字符串插入。所以我认为row_xx.code是一个字符串
要解决这个问题你应该引用"引用" row_xx.code by'像这样的符号:

CheckInventory = "SELECT * FROM inventory WHERE code ='"..row_2.code.."'"


更新
为了解决问题的第二部分并弄清楚价值是否存在,我建议遵循以下几 在旧的普通Java中,当我得到SQLite Cursor时,我可能会检查它是否有这样的行:

if(cursor.moveToFirst())
   // it has at least one value
else
   // it hasn't values at all

当然,Corona也有类似的东西

您还可以使用以下方法更新记录(如果不存在则创建):

// create record IF NOT EXISTS:
String createNonExistentRec = "Insert or ignore into "...// insert key/unique values
db.execSQL(createNonExistentRec, ...);

// update values:
String updateQuery = "..."
...

答案 1 :(得分:0)

我找到了解决方案:

for x in db:urows "select count(*) from inventory" do 
  if x>0 then -- The inventory is empty
    for w in db:urows("SELECT count (*) FROM inventory WHERE code ='"..row_2.code.."'") do
       --The item is already in the inventory
       if w > 0 then 
           CheckInventory = "SELECT * FROM inventory WHERE code ='"..row_2.code.."'"
                   for row_4 in db:nrows(CheckInventory) do
                       updateItemsCode(row_4.code, "inventory", "qtyoninventory", row_4.qtyoninventory+1)
                   end
       else
       --The item is not in the inventory, so we add it! 
            for maxid in db:urows("SELECT MAX(id) FROM inventory") do
                   insertInventory(maxid+1,row_2.code, row_2.name, row_2.src, row_2.desc, "no",1,row_2.price,row_2.usetxt)
             end
       end
    end
 else
    insertInventory(1,row_2.code, row_2.name, row_2.src, row_2.desc, "no",1,row_2.price,row_2.usetxt)
 end
end