AndroidSQLite(一)

  Android系统集成了一个轻量级的数据库:SQLite,SQLite是一个嵌入式的数据库引擎,专门适用于资源有限的设备上(手机、PDA)的适量数据存储。

  Android提供了SQLiteDatabase,它代表了一个SQLite数据库(底层就是一个数据文件),在个数据库中理论上是可以存在无限多个表的。一旦应用程序获得了代表指定数据库的SQLiteDatabase对象,就可以通过SQLiteDatabase对象来操作SQLite数据库。

  SQLiteDatabase提供了几个静态的方法来打开一个文件对应的数据库,此处介绍几个常用的:

  •   static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags):打开path文件所代表的SQLite数据库。
  •   static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory):打开或创建(如果不存在)path文件所代表的SQLite数据库。
  •   static SQLiteDatabase openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory):打开或创建(如果不存在)file文件所代表的SQLite数据库。

  在得到SQLiteDatabase对象之后,就可以调用方法执行SQL语句了,在此处介绍几个常用的方法,是直接执行SQL语句的,需要有SQL语法基础,如果不熟悉SQL语法,SQLiteDatabase还提供了其他代替方法,此处不在此介绍。

  •   void execSQL(String sql):执行无返回值的SQL语句,如:insert、delete、update。
  •   void execSQL(String sql, Object[] bindArgs):执行带占位符的SQL语句,占位符用?表示。
  •   Cursor rawQuery(String sql, String[] selectionArgs):执行一个带占位符的查询,返回一个Cursor对象。
  •   void beginTransaction():开始事务。
  •   void endTransaction ():结束事务。
  •   void close ():关闭数据库

  对于查询方法,会返回一个Cursor对象,Cursor提供如下方法来移动查询结果的记录指针。

  • abstract boolean move(int offset):将记录指针向上或向下移动指定的行数。offset为正数就是向下移动;为负数就是向上移动。
  • abstract boolean moveToFirst():将记录指针移动到第一行,如果移动成功则返回true。
  • abstract boolean moveToLast():将记录指针移动到最后行,如果移动成功则返回true。
  • abstract boolean moveToNext():将记录指针移动到下一行,如果移动成功则返回true。
  • abstract boolean moveToPosition(int position):将记录指针移动到指定的行,如果移动成功则返回true。
  • abstract boolean moveToPrevious():将记录指针移动到上一行,如果移动成功则返回true。
  • abstract Xxx getXxx(int columnIndex):获取该行的指定列的数据。

示例:创建一个数据库并往其中插入数据。

Java Code
 1 public class main extends Activity {
 2     SQLiteDatabase db;
 3     Button bn = null;
 4     ListView listView;
 5     @Override
 6     public void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.main);
 9         
10       //创建或打开数据库(此处需要使用绝对路径)
11               db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir()
12                   .toString() + "/my.db3" , null);        
13               listView = (ListView)findViewById(R.id.show);
14               bn = (Button)findViewById(R.id.ok);
15               bn.setOnClickListener(new OnClickListener()
16               {
17   
18                   public void onClick(View source)
19                   {
20                       //获取用户输入
21                       String title = ((EditText)findViewById(R.id.title))
22                           .getText().toString();
23                       String content = ((EditText)findViewById(R.id.content))
24                           .getText().toString();
25                       try 
26                       {
27                           insertData(db , title , content);
28                           Cursor cursor = db.rawQuery("select * from news_inf", null);
29                           inflateList(cursor);
30                       }
31                       catch(SQLiteException  se)
32                       {
33                           //执行DDL创建数据表
34                           db.execSQL("create table news_inf(_id integer primary key autoincrement,"
35                               + " news_title varchar(50),"
36                               + " news_content varchar(255))");
37                           //执行insert语句插入数据
38                           insertData(db , title , content);
39                           //执行查询
40                           Cursor cursor = db.rawQuery("select * from news_inf", null);
41                           inflateList(cursor);
42                       }
43                   }            
44               });        
45     }
46     
47     private void insertData(SQLiteDatabase db
48             , String title , String content)
49         {
50             //执行插入语句
51             db.execSQL("insert into news_inf values(null , ? , ?)"
52                 , new String[]{title , content});
53         }
54         private void inflateList(Cursor cursor)
55         {
56             //填充SimpleCursorAdapter
57             SimpleCursorAdapter adapter = new SimpleCursorAdapter(
58                     main.this , R.layout.line, cursor 
59                 , new String[]{"news_title" , "news_content"}
60                 , new int[]{R.id.my_title , R.id.my_content});
61             //显示数据
62             listView.setAdapter(adapter);
63         }
64         @Override
65         public void onDestroy()
66         {
67             super.onDestroy();
68             //退出程序时关闭SQLiteDatabase
69             if (db != null && db.isOpen())
70             {
71                 db.close();
72             }
73         }
74     
75 }

  PS:通过File Explorer查看Android模拟器文件,发现新创建的数据库文件在data/data/<package name>/files/目录下面。

  总结起来,使用SQLiteDatabase对象进行SQLite数据库操作的大致步骤如下:

  1. 获取SQLiteDatabase对象,它代表了与SQLite数据库的连接。
  2. 调用SQLiteDatabase对象的方法来执行SQL语句。
  3. 操作SQL语句的执行结果。
  4. 关闭SQLiteDatabase对象,回收资源。

  sqlite3

  在Android的SDK中,提供了一个名为sqlite3.exe的工具(在tools文件夹下)。它是一个简单的SQLite数据库管理工具,类似于MySQL提供的命令行窗口。

  SQLite支持的数据类型

  SQLite内部只支持NULL、INTEGER、REAL(浮点型)、TEXT(文本)、BLOB(大二进制对象)这五种数据类型。但是实际上SQLite完全可以接受varchar、char、decimal等数据类型,只不过SQLite会在运算或保存时将他们转换为上面5种数据类型中相应的类型,所以开发者可以不关心声明该字段所使用的数据类型。

  唯一例外的情况是:定义为INTEGER PRIMARY KEY的字段只能存储64位整数,当向其插入其他类型数据的时候,SQLite会产生错误。

  SQLite的事务

  SQLite也支持事务机制,前面已经介绍了SQLiteDatabase包含的两个控制事务的方法:beginTransaction(开始事务)和endTransaction(结束事务)。除此之外SQLiteDatabase对象还提供了inTransaction方法判断上下文是否处于事务中,处于返回true,否则返回false。

  对于数据库的操作,SQLiteDatabase如何判断提交事务还是回滚事务?

  SQLiteDatabase对象中还存在一个方法setTransactionSuccessful,用于设置事务的标识,如果程序事务执行中调用该方法设置了事务成功,则提交事务,否则程序将回滚事务。最好配合try--finally来处理。

示例:

 1         public void insertDB()
 2         {
 3             db.beginTransaction();//开始事务
 4             try
 5             {
 6                 //执行DDL创建数据表
 7                 db.execSQL("create table news_inf(_id integer primary key autoincrement,"
 8                     + " news_title varchar(50),"
 9                     + " news_content varchar(255))");
10                 //执行insert语句插入数据
11                 insertData(db , "title" , "content");
12                 //执行查询
13                 Cursor cursor = db.rawQuery("select * from news_inf", null);
14                 inflateList(cursor);
15                 db.setTransactionSuccessful();//执行完设置事务成功;否则endTransaction方法将回滚。
16             }
17             finally
18             {
19                 db.endTransaction();//结束事务
20             }
21         }

  

原文地址:https://www.cnblogs.com/plokmju/p/2969274.html