在Android中查询SQLite(插入查询)

6
我想将一个表单的值插入到数据库中,其中有两个整数和一个字符串,但我无法在我的SQLite数据库查看器中看到我输入的值。我使用以下代码:
SQLiteDatabase myDB= null;
      String TableName = "basicdetai";
     try{ 

          myDB = this.openOrCreateDatabase("Medical", MODE_PRIVATE, null); 

          /* Create a Table in the Database. */
         myDB.execSQL("CREATE TABLE IF NOT EXISTS "
            + TableName
            + " (order_id INT(4), doc_id INT(4),doc_name VARCHAR );");
         /* Insert data to a Table*/
          myDB.execSQL("INSERT INTO "
            + TableName
            + "(order_id,doc_id,doc_name)"
           + " VALUES ("+ ordid + ","+ doci + ","+ docnam +");");
        // line 10  + " VALUES ("+ a + ","+ b + ","+ docnam +");");
        //  line 11  +"VALUES (5011,4011,'gupta');");



      }
      catch(Exception e) {
          Log.e("Error", "Error", e);
         } 
      finally {
           if (myDB != null)
            myDB.close();
          }

但是当我在上面的代码中使用第11行时,我可以通过SQLite浏览器看到记录(5011,4011,'gupta')。 我正在执行以下操作将从表单获取的字符串值转换为整数。

try {
          ordid = Integer.parseInt(orderid.getText().toString());
          doci = Integer.parseInt(docid.getText().toString());
         // qn = Integer.parseInt(qty.getText().toString());
      } catch(NumberFormatException nfe) {
         System.out.println("Could not parse " + nfe);
      }

请帮忙...

确切的问题是什么?如果您能正确格式化代码,阅读起来会更容易。 - Stephan
3个回答

13
请尝试以下查询...
db.execSQL("insert into your table name (order_id,doc_id,doc_name)" + "values("ordid+","+doci+","
                + "\"" + docnam + "\"" + ") ;");

谢谢Chirag..所以字符串需要使用双引号插入..非常感谢。:):) - Adi
Chirag,如果您能给我建议一些书籍或网站,那将是非常有帮助的,因为我的工作涉及大量的查询编写。我正在进行我的第一个Android项目。这个表格可以从不同的活动中访问吗? - Adi
你需要创建一个数据库类,并将所有查询语句写入其中,这样你就可以从任何地方访问它。 - Chirag
实际上,我想在按钮点击时将值插入数据库。我有三个按钮,每个按钮执行不同的任务。其中一个按钮将值插入数据库。因此,我使用switch case来执行任务。现在,我要通过创建单独的数据库类来完成上述任务,有没有什么方法? - Adi
出于安全考虑,请使用绑定参数。 - Hesham Yassin

11

Android有一些辅助类可以帮助进行插入操作。为什么不使用它们呢?

示例:

    public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put("title", item.getTitle());
    row.put("author", item.getAuthor());
    row.put("publisher", item.getPublisher());
    row.put("thumbnailUrl", item.getThumbnail());
    row.put("formatType", item.getFormat());
    row.put("contentUrl", item.getContentUrl());
    row.put("publicationType", item.getPublicationType());
    row.put("favorite", item.isFavorite() ? "YES" : "NO");
    row.put("id", item.getItemId());
    row.put("normalizedTitle", StringUtil.normalize(item.getTitle()));
    row.put("downloaded", item.hasContent() ? Calendar.getInstance()
            .getTimeInMillis() : 0);
    row.put("wasdownloaded", item.hasContent() ? "YES" : "NO");
    row.put("bookmarked", "NO");
    row.put("archived", "NO");

    long id = db.insert("LIBRARY", null, row);
    }

3
Simple and easy to understand In this code i am using two fields.
//Activity.java

package com.virtual.university;

import java.util.Locale;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class VirtualActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
     private String tablename="StudentInfo";
     EditText t1,t2;
     Button b1,b2;
     SQLiteDatabase db;
     public static final String CONTENT1 = "sid";
     public static final String CONTENT2 = "pasw";
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        t1=(EditText)findViewById(R.id.editText1);
        t2=(EditText)findViewById(R.id.editText2);
        b1=(Button)findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2=(Button)findViewById(R.id.button1);
        b2.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                t1.setText("");
                t2.setText("");
            }
        });
        // create or open database file
        db = openOrCreateDatabase("Login.db" , SQLiteDatabase.CREATE_IF_NECESSARY,null);
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);

        //Create table
        db.execSQL("CREATE TABLE IF NOT EXISTS "+tablename+" " +
                "( "+CONTENT1+" INTEGER PRIMARY KEY AUTOINCREMENT," +
                "  "+CONTENT2+" TEXT ); ");
       //TextView txtView=(TextView)findViewById(R.id.txtView);
       //txtView.setText("Table created");
    }
    public void onClick(View v) 
    {
    insert();   
    }
    private void insert() {

        int uid=Integer.parseInt(t1.getText().toString());
        String pwd=t2.getText().toString();
        String sql1 = "insert into " +tablename+ " (" +CONTENT1+ ", " +CONTENT2+ ") values(" +uid+  ",'" +pwd+ "')";
        db.execSQL(sql1);
        Toast.makeText(getBaseContext(),"inserted", Toast.LENGTH_SHORT).show(); 
    }}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接