Android數據庫的創建,插入,查詢等


1.一個新的數據庫的創建及打開方式

關於Android數據庫的創建,官方文檔里面推薦的是繼承SQLiteOpenHelper創建子類,重寫onCreate方法來創建一個新的SQLiteDatabase。

在這里需要強調的幾點有:

1).數據庫在第一次創建的時候,才調用onCreate方法,也就是說一旦某一個數據庫已經被創建好了,那么就不用再調用onCreate方法了。

2).在onCreate執行sql語句,創建數據庫表。

3).向數據庫表里面寫入數據或者讀取數據的時候,首先得實例化SQLiteOpenHelper子類,通過該子類調用getReadableDatabase()或者getWritadableDatabase()方法來打開數據庫。

讀取數據時調用getReadableDatabase(),例如對數據庫數據進行查詢操作。

寫入數據時調用getWritadableDatabase(),例如對數據庫數據進行插入、刪除、更新操作。

 

2.以下是創建SQLiteOpenHelper子類的實現代碼

 1 public class MyDataBaseHelper extends SQLiteOpenHelper {
 2    /*
 3    * context:上下文
 4    * databaseName:創建的數據庫名稱
 5    * databaseVersion:數據庫版本
 6    * */
 7     public MyDataBaseHelper(Context context,String databaseName,int databaseVersion){
 8         super(context,databaseName,null,databaseVersion);
 9     }
10     /*
11     * 數據庫第一次創建的時候,調用onCreate;數據庫已經創建成功之后,就不調用它了
12     * db就是創建的數據庫
13     * db.execSQL這句是用來創建數據庫表
14     * */
15     @Override
16     public void onCreate(SQLiteDatabase db) {
17         System.out.println("數據庫創建成功");
18         db.execSQL("create table imagetable(_id integer primary key autoincrement,word varchar(255),detail varchar(255))");//執行創建表的sql語句
19     }
20 
21     @Override
22     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
23 
24     }
25 }

 

3.實踐操作:創建名為image.db的數據庫,創建數據庫表imagetable,向數據庫表插入數據,同時讀取數據。

插入數據的方式有兩種,一種是通過SQLiteDatabase的execSQL(String sql)方法來實現。一種是通過SQLiteDatabase已經封裝好的insert()方法來實現。個人認為,為了避免由於sql語法導致的程序出錯,使用的后者更加便捷。

查詢數據的時候,使用的是SQLiteDatabase的query()方法,該方法返回的是一個Cursor對象,它就像是一個可移動的游標,可以指向數據庫表的每一行。當cursor移動到某一列的某一行的時候,通過調用cursor的getString()、getInt()、getDouble()等方法獲得該位置的數據。

另外關於SQLiteDatabase的query(table,columns,selection,selectionArgs,groups,having,orderBy,limit)方法的各參數使用在這里進行一個說明吧:

1).table:要查詢的數據庫表名。

2).columns:要查詢的列名。為null的話,返回所有列。

3).selection:查詢條件子句。相當於select語句where關鍵字后面的條件子句部分,在條件子句中允許使用占位符?返回符合該條件子句的行。為null的話,返回所有行。

4).selectionArg:對應seletion參數里面的占位符?的值,值在數組中的位置與占位符在語句中的位置必須一致,否則拋出異常。

5).groups,having,orderBy就分別相當於select語句里面的group By,having,order By關鍵字后面的部分。

6).limit:相當於select語句limit關鍵字后面的部分,指定偏移量和獲取的記錄數。

實現代碼:

 1 public class MainActivity extends AppCompatActivity {
 2     MyDataBaseHelper myDataBaseHelper;
 3     Button insertBtn;
 4     Button searchBtn;
 5     EditText editText1;
 6     EditText editText2;
 7     TextView textView;
 8     String DataBase_Name="image.db";
 9     String Table_Name = "imagetable";
10 
11     @Override
12     protected void onCreate(Bundle savedInstanceState) {
13         super.onCreate(savedInstanceState);
14         setContentView(R.layout.activity_main);
15         //執行該句時,數據庫不被創建
16         myDataBaseHelper = new MyDataBaseHelper(MainActivity.this, DataBase_Name, 2);
17         editText1 = (EditText) findViewById(R.id.edit1);
18         editText2 = (EditText) findViewById(R.id.edit2);
19         insertBtn = (Button) findViewById(R.id.insertBtn);
20         searchBtn = (Button) findViewById(R.id.searchBtn);
21         textView = (TextView) findViewById(R.id.textview);
22         insertBtn.setOnClickListener(new View.OnClickListener() {
23             @Override
24             public void onClick(View v) {
25                 String word = editText1.getText().toString();
26                 String detail = editText2.getText().toString();
27                 ContentValues contentValues = new ContentValues();
28                 contentValues.put("word", word);
29                 contentValues.put("detail", detail);
30                 //插入數據:getWritableDatabase,當執行getWritableDatabase時數據庫才被創建
31                 SQLiteDatabase db = myDataBaseHelper.getWritableDatabase();
32                 long id = db.insert(Table_Name, null, contentValues);
33                 db.close();
34                 if (id != -1) Toast.makeText(MainActivity.this, "插入成功", Toast.LENGTH_SHORT).show();
35                 else Toast.makeText(MainActivity.this, "插入失敗", Toast.LENGTH_SHORT).show();
36             }
37         });
38         searchBtn.setOnClickListener(new View.OnClickListener() {
39             @Override
40             public void onClick(View v) {
41                 //查詢數據:getReadableDatabase
42                 searchDataBase(myDataBaseHelper.getReadableDatabase());
43                 Toast.makeText(MainActivity.this, "搜索成功", Toast.LENGTH_SHORT).show();
44             }
45         });
46     }
47 
48     private void searchDataBase(SQLiteDatabase db) {
49         Cursor cursor=db.query("imagetable", new String[]{"word","detail"}, null, null, null, null, null);
50         String word = "";
51         String detail = "";
52         for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
53            word = cursor.getString(0) + "\n";
54            detail = cursor.getString(1) + "\n";
55         }
56         cursor.close();
57         db.close();
58         String s = word +detail;
59         textView.setText(s);
60     }
61 
62     @Override
63     protected void onDestroy() {
64         super.onDestroy();
65         if (myDataBaseHelper != null)
66             myDataBaseHelper.close();
67     }
68 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM