Android编程之数据库Sql编程实例分析

时间:2022-02-18 08:47:32

本文实例讲述了Android编程数据库Sql编程实现方法。分享给大家供大家参考。具体分析如下:

Android中安装轻量级数据库Sqlite,现在测试数据库基本操作。

数据库基本操作:创建表,插入,删除可以用execSQL();读取可以用rawQuery();这两个函数都可以标准SQL语句进行操作。

源代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.test.sql;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
public class test_sql extends Activity
{
 DatabaseHelper mOpenHelper;
 private static final String DATABASE_NAME = "test.db";
 private static final int DATABASE_VERSION = 1;
 private static class DatabaseHelper extends SQLiteOpenHelper {
  DatabaseHelper(Context context) {
   super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }
  @Override
  public void onCreate(SQLiteDatabase db)
  {
   //新建一个用户表
   //共有5项:Id Pwd Name OnLineTime Level
   db.execSQL("CREATE TABLE User_Table ('Id' INT,'Pwd' VARCHAR,'Name' VARCHAR,'OnLineTime' INT,'Level' INT)");
  }
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
 }
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mOpenHelper = new DatabaseHelper(this);
  SQLiteDatabase db = mOpenHelper.getWritableDatabase();
  //清空数据
  db.execSQL("DELETE FROM User_Table");
  //插入数据10000 123456 "jdh" 0 0
  //插入数据10001 123456 "jim" 0 0
  db.execSQL("INSERT INTO User_Table VALUES (?,?,?,?,?)", new Object[]{10000,"123456","jdh",0,0});
  db.execSQL("INSERT INTO User_Table VALUES (?,?,?,?,?)", new Object[]{10001,"123456","jim",0,0});
  //读取数据
  Cursor cursor = db.rawQuery("SELECT * FROM User_Table WHERE Name = ?",new String[]{"jdh"});
  while (cursor.moveToNext())
  {
   String str = cursor.getInt(0) + cursor.getString(1) + cursor.getString(2) + cursor.getInt(3) + cursor.getInt(4);
   Log.i("str:", str);
  
 }
}

希望本文所述对大家的Android程序设计有所帮助。