带有约束

时间:2018-04-19 09:38:35

标签: android sql azure-sql-database

我正忙着在android studio中编写一个insert语句,首先要检查数据是否存在于数据库中,如果没有,则必须插入它。

    if (name.trim().equals("") || supp.trim().equals("") || range.trim().equals("") || size.equals("") || price.equals(""))
        z = "Please enter all fields";
    else {
        try {
            con = connectionclass();      // Connect to database
            if (con == null) {
                z = "Check Your Internet Access!";
            } else {
                String query = "BEGIN" +
                        "IF NOT EXISTS(Select * from cc_lining)" +
                        "BEGIN " +
                        "INSERT INTO cc_lining (lining_id,lining_name, lining_range, lining_supplier, lining_width, lining_unit_price) VALUES ('" + id.toString() + "','" + name.toString() + "','" + range.toString() + "','" + supp.toString() + "','" + size.toString() + "','" + price.toString() + "')" +
                        "END" +
                        "END";
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                if (rs.next()) {
                    isSuccess = true;
                    con.close();
                } else {
                    z = "Invalid!";
                    isSuccess = false;
                }
            }
        } catch (Exception ex) {
            isSuccess = false;
            z = ex.getMessage();
        }
    }
    return z;

当我运行代码时,我收到错误Incorrect Syntex near NOT

1 个答案:

答案 0 :(得分:1)

  

NOT

附近的Syntex不正确

逻辑

首先运行 SELECT语句尊重主键,例如 lining_id

<强>样本

 Cursor cursor = null;
 String sql ="SELECT * FROM cc_lining WHERE lining_id=" + id + "; 
 cursor= db.rawQuery(sql,null);

 if(cursor.getCount()>0){
  // Data Fount. Query for UPDATE 
 }else{
  // Data Not Found. You should INSERT your Record.

 }
 cursor.close();