如何在SQLite中执行操作之前检查记录中是否存在数据?

时间:2017-11-26 11:06:50

标签: android sqlite android-sqlite qr-code

我制作了一个扫描qr代码的应用。我希望将从qr代码扫描的数据(如2300,2301,2302之类的数字)与sqlite数据库中名为ID的列进行比较。 sqlite数据库中列ID的一些值是2301,2302,2303。我希望扫描的数据与ID中的值进行比较,如果匹配,则执行操作。如果不是,将显示错误消息。如果qr代码具有值2301,则将执行该动作。如果它是8900(数据库中没有的数字),则会显示一条消息:找不到学生。我还想澄清一下,扫描数据没有输入sqlite数据库,而是发送到谷歌脚本链接。 sqlite数据库包含学生列表。我希望如果扫描的数据与sqlite数据库中的nay ID不相似,那么sannedData将不会发送到谷歌应用程序脚本目标。 这是我的数据库代码,用于活动DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "SURNAME";
public static final String COL_4 = "MARKS";

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME +" (ID INT PRIMARY KEY UNIQUE,NAME TEXT,SURNAME TEXT,MARKS TEXT)");
}

下面是我想要修改的代码,以检查它是否在数据库中。这是另一项名为MainActivity的活动。

    public class ArrivalTime extends AppCompatActivity {

    String scannedData;
    Button scanBtn;

    //-----------------------------------------------------------
    //DatabaseHelper myDb;
//------------------------------------------------------------


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_arrival_time);
        final Activity activity = this;
        scanBtn = (Button) findViewById(R.id.scan_btn);
        //-------------------------------------------------------
     //  myDb = new DatabaseHelper(this);

        //---------------------------------------------------------

        scanBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentIntegrator integrator = new IntentIntegrator(activity);
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
                integrator.setPrompt("Place barcode in window to Scan it");
                integrator.setBeepEnabled(true);
                integrator.setCameraId(0);
                integrator.setBarcodeImageEnabled(false);
                integrator.initiateScan();
            }

        });

    }

    //-----------------------------------------------------------------------------------------

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result= IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
        if(result!=null){
            scannedData = result.getContents();
            if(scannedData != null){
                // here we need to handle scanned data
               // Cursor c = myDb.getId(String);
               // if(c.getCount() == 0) {
                    // show message
                 //   Toast.makeText(ArrivalTime.this,"Student doesn't exist in database",Toast.LENGTH_LONG).show();
                 //   return;
                //}
                new SendRequest().execute();

            }
            else{

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    //-----------------------------------------------------------------------------------------

    public class SendRequest extends AsyncTask<String, Void, String>{

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0){

            try{
                URL url = new URL("https://script.google.com/macros/s/ttttttttttttttttttttttttttttttttttttttttttttt/exec");

                JSONObject postDataParams = new JSONObject();

                postDataParams.put("sdata",scannedData);
                Log.e("params", postDataParams.toString());

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            }
            catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();

        }
    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
//-----------------------------------------------------------------------------------------

我希望函数检查扫描的数据是否为空并且数据库中是否存在。我尝试过if(scanningData!= null&amp;&amp;&scan; = id)但我不确定如何从另一个活动调用数据库数据并执行比较

我在下面给出了一个例子,但它假设我正在检查是否存在与扫描的内容相似的值,以便可以将其输入sqlite数据库,这不是我想要的。

任何建议。

2 个答案:

答案 0 :(得分:0)

您可以查看如下..

@Data
@Entity
@Table(name = "user_card")
public class UserCard implements Serializable {

@Id
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;

@Id
@ManyToOne
@JoinColumn(name = "card_id", nullable = false)
private Card card;

@Column(name = "cardCount", nullable = false)
private int cardCount;
}

答案 1 :(得分:0)

答案非常简单,您必须使用ID列的给定值进行选择查询,并像这样检查Cursor.getCount()方法。 Cursor.getCount(); // returns number of rows from this query。 如果它返回0,那么那里有一些行意味着ID确实存在

public boolean Contains(String ID) {
    Cursor cursor = null;

    cursor = db.rowQuery("SELECT * FROM student_table WHERE ID === ? ", new String[]{ID});
    if (cursor.getCount() == 0) {
        return false;
    }
    return true;
}