实验 11 SQLite数据库的使用
SQLiteDatabase的使用

SQLiteDatabase的使⽤新建DBHeler.JAVA1package com.hixin.db;23import java.util.ArrayList;4import java.util.HashMap;56import er;78import android.content.ContentValues;9import android.content.Context;10import android.database.Cursor;11import android.database.sqlite.SQLiteDatabase;12import android.database.sqlite.SQLiteOpenHelper;1314public class DBHelper extends SQLiteOpenHelper{15public final static String DB_NAME = "contact";16public final static int VERSION = 1;17private static DBHelper instance = null;18private SQLiteDatabase db;1920//单例模式21private DBHelper(Context context) {22super(context,DB_NAME,null,VERSION);23 }2425public static DBHelper getInstance(Context context) {26if(instance == null) {27 instance = new DBHelper(context);28 }29return instance;30 }31private void openDatabase() {32if(db == null) {33 db = this.getReadableDatabase();34 }35 }3637 @Override38public void onCreate(SQLiteDatabase db) {39// TODO Auto-generated method stub40 StringBuffer tableCreate = new StringBuffer();41 tableCreate.append("create table user (_id integer primary key autoincrement,")42 .append("name text,")43 .append("mobilephone text,")44 .append("familyphone text,")45 .append("officephone text,")46 .append("position text,")47 .append("company text,")48 .append("address text,")49 .append("email text,")50 .append("othercontact text,")51 .append("zipcode text,")52 .append("remark text,")53 .append("imageid int)");5455 db.execSQL(tableCreate.toString());56 }5758 @Override59public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {60// TODO Auto-generated method stub61 String sql = "drop table if exists user";62 db.execSQL(sql);63 onCreate(db);64 }6566public long save(User user) {67 openDatabase();68 ContentValues value = new ContentValues();69 value.put("name", ername);70 value.put("mobilephone", user.mobilePhone);71 value.put("familyphone", user.familyPhone);72 value.put("officephone", user.officePhone);73 value.put("position", user.position);74 value.put("address", user.address);75 value.put("email", user.email);76 value.put("othercontact", user.otherContact);77 value.put("zipcode", user.zipCode);78 value.put("remark", user.remark);79 value.put("imageid", user.imageId);8081return db.insert("user", null, value);82 }8384public ArrayList getUserList() {85 openDatabase();86 Cursor cursor = db.query("user", null, null, null, null, null, null);87 ArrayList list = new ArrayList();88while (cursor.moveToNext()) {89 HashMap map = new HashMap();90 map.put("imageid", cursor.getInt(cursor.getColumnIndex("imageid")));91 map.put("name", cursor.getString(cursor.getColumnIndex("name")));92 map.put("mobilephone", cursor.getString(cursor.getColumnIndex("mobilephone")));93 list.add(map);94 }95return list;96 }9798 }主函数中调⽤//save user to databaseDBHelper.getInstance(MainActivity.this).save(user);save()调⽤openDatabase(),如果数据库不存在,则⾃动调⽤数据库的onCreate()//检索数据库ArrayList data = DBHelper.getInstance(this).getUserList();tv_name.setText((CharSequence) ((HashMap) data.get(position)).get("name"));另外⼀种版本package com.example.healthembed;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import com.example.healthembed.dummy.BloodPre;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.widget.Toast;public class DatabaseHelper extends SQLiteOpenHelper {private static final String DB_NAME = "person.db"; //数据库名称private static final int version = 1; //数据库版本private static DatabaseHelper instance = null;private SQLiteDatabase db;//单例模式public static DatabaseHelper getInstance(Context context) {if(instance == null) {instance = new DatabaseHelper(context);}return instance;}private void openDatabase() {if(db == null) {db = this.getReadableDatabase();}}public DatabaseHelper(Context context) {super(context, DB_NAME, null, version);}@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub/* StringBuffer tableCreate = new StringBuffer();tableCreate.append("create table user (_id integer primary key autoincrement,").append("hp int,").append("lp int)");db.execSQL(tableCreate.toString());*/String tableCreate = new String();tableCreate="create table user (_id integer primary key autoincrement,name varchar(16),pdate text,hp int,lp int)"; db.execSQL(tableCreate);// Toast.makeText(MyApplication.getContext(), "数据保存成功", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubString sql = "drop table if exists user";db.execSQL(sql);onCreate(db);}public long save(BloodPre user) {openDatabase();ContentValues value = new ContentValues();value.put("name", );value.put("pdate",user.time);value.put("hp", user.highp);value.put("lp", user.lowp);return db.insert("user", null, value);}public ArrayList getUserList() {openDatabase();Cursor cursor = db.query("user", null, null, null, null, null, null);ArrayList<Map> list = new ArrayList();while (cursor.moveToNext()) {HashMap map = new HashMap();map.put("name", cursor.getInt(cursor.getColumnIndex("name")));map.put("pdate", cursor.getString(cursor.getColumnIndex("pdate")));map.put("hp", cursor.getInt(cursor.getColumnIndex("hp")));map.put("lp", cursor.getInt(cursor.getColumnIndex("lp")));list.add(map);}return list;}}View Code封装性更好的,适合建⽴多个表!package com.example.health.util;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.example.health.bp.DatabaseHelper;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;/*** @author wuzhixin* 有if语句的地⽅添加 else if代码就⾏* ⽬的在于⽤⼀个SQLiteOpenHelper⼦类创建多个表,并且表之间是独⽴的,不会⼀下在创建多个表*/public class GeneralDbHelper extends SQLiteOpenHelper{private static final String DB_NAME = "person.db"; //数据库名称private static final int version = 1; //数据库版本private static GeneralDbHelper instance = null;private SQLiteDatabase db;private Object bean;//单例模式public static GeneralDbHelper getInstance(Context context,Object userType) {if(instance == null) {instance = new GeneralDbHelper(context,userType);}return instance;}private void openDatabase() {if(db == null) {db = this.getReadableDatabase();}}public GeneralDbHelper (Context context,Object userType) {super(context, DB_NAME, null, version);this.bean = userType;}/* (non-Javadoc)* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)*/@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub/* StringBuffer tableCreate = new StringBuffer();tableCreate.append("create table user (_id integer primary key autoincrement,").append("hp int,").append("lp int)");db.execSQL(tableCreate.toString());*/String tableCreate = new String();if(bean instanceof User) {tableCreate = "CREATE TABLE zhongduanuser (shenfennum varchar(255) primary key,name varchar(64),regtime varchar(255),address varchar(255), birthdate varchar(255))"; db.execSQL(tableCreate);}// Toast.makeText(MyApplication.getContext(), "数据保存成功", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubif(bean instanceof User) {String sql = "drop table if exists zhongduanuser";db.execSQL(sql);}onCreate(db);}public long save(Object obj) {openDatabase();ContentValues value = new ContentValues();if(obj instanceof User) {/*private String shenfennum;private String name;private String regtime;private String address;private String birthdate;*/value.put("shenfennum", ((User)obj).getShenfennum());value.put("name", ((User)obj).getName());value.put("regtime", ((User)obj).getRegtime());value.put("address", ((User)obj).getAddress());value.put("birthdate", ((User)obj).getBirthdate());return db.insert("zhongduanuser", null, value);}else{return 0;}}public List<?> getBeanList() {openDatabase();if(bean instanceof User) {Cursor cursor = db.query("zhongduanuser", null, null, null, null, null, null);List<User> list = new ArrayList<User>();while (cursor.moveToNext()) {User user = new User();user.setShenfennum(cursor.getString(cursor.getColumnIndex("shenfennum")));user.setName(cursor.getString(cursor.getColumnIndex("name")));user.setRegtime(cursor.getString(cursor.getColumnIndex("regtime")));user.setAddress(cursor.getString(cursor.getColumnIndex("address")));user.setBirthdate(cursor.getString(cursor.getColumnIndex("birthdate")));list.add(user);}return list;}else {return null;}}}View Code保存数据://创建数据库,保存⽤户信息到本地for (User suser : erList) {GeneralDbHelper.getInstance(MyApplication.getContext(), suser).save(suser);}使⽤数据:User user = new User();erList = GeneralDbHelper.getInstance(MyApplication.getContext(), user).getBeanList();上⾯的不能正确使⽤,下⾯的这个可以package com.example.health.util;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;* @author wuzhixin* 有if语句的地⽅添加 else if代码就⾏* ⽬的在于⽤⼀个SQLiteOpenHelper⼦类创建多个表,并且表之间是独⽴的,不会⼀下在创建多个表*/public class GeneralDbHelper extends SQLiteOpenHelper{private static final String DB_NAME = "person.db"; //数据库名称private static final int version = 1; //数据库版本private static GeneralDbHelper instance = null;private SQLiteDatabase db;//单例模式public static GeneralDbHelper getInstance(Context context) {if(instance == null) {instance = new GeneralDbHelper(context);}return instance;}private void openDatabase() {if(db == null) {db = this.getReadableDatabase();}}public GeneralDbHelper (Context context) {super(context, DB_NAME, null, version);}/* (non-Javadoc)* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)*/@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub/* StringBuffer tableCreate = new StringBuffer();tableCreate.append("create table user (_id integer primary key autoincrement,").append("hp int,").append("lp int)");db.execSQL(tableCreate.toString());*/String tableCreate1 = "CREATE TABLE zhongduanuser (shenfennum varchar(255) primary key,name varchar(64),regtime varchar(255),address varchar(255), birthdate varchar(255))"; db.execSQL(tableCreate1);String tableCreate2="create table xueya2 (_id integer primary key autoincrement,userid varchar(255),regdate varchar(64),shousuo int(11),shuzhang int(11),maibo int(11))";db.execSQL(tableCreate2);// Toast.makeText(MyApplication.getContext(), "数据保存成功", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubString sql1 = "drop table if exists zhongduanuser";db.execSQL(sql1);String sql2 = "drop table if exists xueya2";db.execSQL(sql2);onCreate(db);}public long save(Object obj) {openDatabase();ContentValues value = new ContentValues();if(obj instanceof User) {/*private String shenfennum;private String name;private String regtime;private String address;private String birthdate;*/value.put("shenfennum", ((User)obj).getShenfennum());value.put("name", ((User)obj).getName());value.put("regtime", ((User)obj).getRegtime());value.put("address", ((User)obj).getAddress());value.put("birthdate", ((User)obj).getBirthdate());return db.insert("zhongduanuser", null, value);}else if(obj instanceof BloodPre){/*private String userid;private String time;private int highp;private int lowp;private int pulse;*/value.put("userid", ((BloodPre)obj).getUserid());value.put("regdate", ((BloodPre)obj).getTime());value.put("shousuo", ((BloodPre)obj).getHighp());value.put("shuzhang", ((BloodPre)obj).getLowp());value.put("maibo", ((BloodPre)obj).getPulse());return db.insert("xueya2", null, value);}else{return 0;}}public List<?> getBeanList(Object obj) {openDatabase();if(obj instanceof User) {Cursor cursor = db.query("zhongduanuser", null, null, null, null, null, null);List<User> list = new ArrayList<User>();while (cursor.moveToNext()) {User user = new User();user.setShenfennum(cursor.getString(cursor.getColumnIndex("shenfennum")));user.setName(cursor.getString(cursor.getColumnIndex("name")));user.setRegtime(cursor.getString(cursor.getColumnIndex("regtime")));user.setAddress(cursor.getString(cursor.getColumnIndex("address")));user.setBirthdate(cursor.getString(cursor.getColumnIndex("birthdate")));list.add(user);}return list;}else if(obj instanceof BloodPre){Cursor cursor = db.query("xueya2", null, null, null, null, null, null);List<BloodPre> list = new ArrayList<BloodPre>();while (cursor.moveToNext()) {BloodPre bloodpre = new BloodPre();bloodpre.setUserid(cursor.getString(cursor.getColumnIndex("userid")));bloodpre.setTime(cursor.getString(cursor.getColumnIndex("regdate")));bloodpre.setHighp(cursor.getInt(cursor.getColumnIndex("shousuo")));bloodpre.setLowp(cursor.getInt(cursor.getColumnIndex("shuzhang")));bloodpre.setPulse(cursor.getInt(cursor.getColumnIndex("maibo")));list.add(bloodpre);}return list;}else {return null;}}}View Code更新的版本:package com.example.health.util;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;/*** @author wuzhixin** ⽬的在于⽤⼀个SQLiteOpenHelper⼦类创建多个表*/public class GeneralDbHelper extends SQLiteOpenHelper{private static final String DB_NAME = "person.db"; //数据库名称private static final int version = 1; //数据库版本private static GeneralDbHelper instance = null;private SQLiteDatabase db;//单例模式public static GeneralDbHelper getInstance(Context context) {if(instance == null) {instance = new GeneralDbHelper(context);}return instance;}private void openDatabase() {if(db == null) {db = this.getReadableDatabase();}}public GeneralDbHelper (Context context) {super(context, DB_NAME, null, version);}/* (non-Javadoc)* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) */@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub/* StringBuffer tableCreate = new StringBuffer();tableCreate.append("create table user (_id integer primary key autoincrement,").append("hp int,").append("lp int)");db.execSQL(tableCreate.toString());*/String tableCreate1 = "CREATE TABLE zhongduanuser (shenfennum varchar(255) primary key,name varchar(64),regtime varchar(255),address varchar(255), birthdate varchar(255))"; db.execSQL(tableCreate1);String tableCreate2="create table xueya2 (_id integer primary key autoincrement,userid varchar(255),regdate varchar(64),shousuo int(11),shuzhang int(11),maibo int(11))";db.execSQL(tableCreate2);// Toast.makeText(MyApplication.getContext(), "数据保存成功", Toast.LENGTH_SHORT).show();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubString sql1 = "drop table if exists zhongduanuser";db.execSQL(sql1);String sql2 = "drop table if exists xueya2";db.execSQL(sql2);onCreate(db);}public long save(Object obj) {openDatabase();ContentValues value = new ContentValues();if(obj instanceof User) {/*private String shenfennum;private String name;private String regtime;private String address;private String birthdate;*/value.put("shenfennum", ((User)obj).getShenfennum());value.put("name", ((User)obj).getName());value.put("regtime", ((User)obj).getRegtime());value.put("address", ((User)obj).getAddress());value.put("birthdate", ((User)obj).getBirthdate());return db.insert("zhongduanuser", null, value);}else if(obj instanceof BloodPre){/*private String userid;private String time;private int highp;private int lowp;private int pulse;*/value.put("userid", ((BloodPre)obj).getUserid());value.put("regdate", ((BloodPre)obj).getTime());value.put("shousuo", ((BloodPre)obj).getHighp());value.put("shuzhang", ((BloodPre)obj).getLowp());value.put("maibo", ((BloodPre)obj).getPulse());return db.insert("xueya2", null, value);}else{return 0;}}public List<?> getBeanList(Object obj) {openDatabase();if(obj instanceof User) {Cursor cursor = db.query("zhongduanuser", null, null, null, null, null, null);List<User> list = new ArrayList<User>();while (cursor.moveToNext()) {User user = new User();user.setShenfennum(cursor.getString(cursor.getColumnIndex("shenfennum")));user.setName(cursor.getString(cursor.getColumnIndex("name")));user.setRegtime(cursor.getString(cursor.getColumnIndex("regtime")));user.setAddress(cursor.getString(cursor.getColumnIndex("address")));user.setBirthdate(cursor.getString(cursor.getColumnIndex("birthdate")));list.add(user);}return list;}else if(obj instanceof BloodPre){Cursor cursor = db.query("xueya2", null, null, null, null, null, null);List<BloodPre> list = new ArrayList<BloodPre>();while (cursor.moveToNext()) {BloodPre bloodpre = new BloodPre();bloodpre.setUserid(cursor.getString(cursor.getColumnIndex("userid")));bloodpre.setTime(cursor.getString(cursor.getColumnIndex("regdate")));bloodpre.setHighp(cursor.getInt(cursor.getColumnIndex("shousuo")));bloodpre.setLowp(cursor.getInt(cursor.getColumnIndex("shuzhang")));bloodpre.setPulse(cursor.getInt(cursor.getColumnIndex("maibo")));list.add(bloodpre);}return list;}else {return null;}}public List<?> getBeanList(Object obj,String userID) {openDatabase();if(obj instanceof BloodPre){String query = "select regdate,shousuo,shuzhang,maibo from xueya2 where userid = "+userID;Cursor cursor = db.query("xueya2", new String[]{"regdate,shousuo,shuzhang,maibo"},"userid=?", new String[]{userID}, null, null, null); List<BloodPre> list = new ArrayList<BloodPre>();while (cursor.moveToNext()) {BloodPre bloodpre = new BloodPre();bloodpre.setTime(cursor.getString(cursor.getColumnIndex("regdate")));bloodpre.setHighp(cursor.getInt(cursor.getColumnIndex("shousuo")));bloodpre.setLowp(cursor.getInt(cursor.getColumnIndex("shuzhang")));bloodpre.setPulse(cursor.getInt(cursor.getColumnIndex("maibo")));list.add(bloodpre);}return list;}else {return null;}}}View Code存数据://创建数据库,保存⽤户信息到本地for (User suser : erList) {GeneralDbHelper.getInstance(MyApplication.getContext()).save(suser);}取数据:User user = new User();erList = (List<User>) GeneralDbHelper.getInstance(MyApplication.getContext()).getBeanList(user);已有数据库时:1private final String DATABASE_PATH = android.os.Environment2 .getExternalStorageDirectory().getAbsolutePath()3 + "/dictionary";4//定义数据库的名字5private final String DATABASE_FILENAME = "dictionary.db";678private SQLiteDatabase openDatabase()9 {10try11 {12// 获得dictionary.db⽂件的绝对路径13 String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;14 File dir = new File(DATABASE_PATH);15// 如果/sdcard/dictionary⽬录中存在,创建这个⽬录16if (!dir.exists())17 dir.mkdir();18// 如果在/sdcard/dictionary⽬录中不存在19// dictionary.db⽂件,则从res\raw⽬录中复制这个⽂件到20// SD卡的⽬录(/sdcard/dictionary)21if (!(new File(databaseFilename)).exists())22 {23// 获得封装dictionary.db⽂件的InputStream对象24 InputStream is = getResources().openRawResource(25 R.raw.dictionary);26 FileOutputStream fos = new FileOutputStream(databaseFilename);27byte[] buffer = new byte[8192];28int count = 0;29// 开始复制dictionary.db⽂件30while ((count = is.read(buffer)) > 0)31 {32 fos.write(buffer, 0, count);33 }34//关闭⽂件流35 fos.close();36 is.close();37 }38// 打开/sdcard/dictionary⽬录中的dictionary.db⽂件39 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(40 databaseFilename, null);41return database;42 }43catch (Exception e)44 {45 }46//如果打开出错,则返回null47return null;48 }。
sqlite使用说明

Sqlite使用说明一、简介:SQLite是目前最流行的开源嵌入式数据库,和很多其他嵌入式存储引擎相比(NoSQL),如BerkeleyDB、MemBASE等,SQLite可以很好的支持关系型数据库所具备的一些基本特征,如标准SQL语法、事务、数据表和索引等。
事实上,尽管SQLite拥有诸多关系型数据库的基本特征,然而由于应用场景的不同,它们之间并没有更多的可比性。
下面我们将列举一下SQLite的主要特征:1. 管理简单,甚至可以认为无需管理。
2. 操作方便,SQLite生成的数据库文件可以在各个平台无缝移植。
3. 可以非常方便的以多种形式嵌入到其他应用程序中,如静态库、动态库等。
4. 易于维护。
综上所述,SQLite的主要优势在于灵巧、快速和可靠性高。
SQLite的设计者们为了达到这一目标,在功能上作出了很多关键性的取舍,与此同时,也失去了一些对RDBMS关键性功能的支持,如高并发、细粒度访问控制(如行级锁)、丰富的内置函数、存储过程和复杂的SQL 语句等。
正是因为这些功能的牺牲才换来了简单,而简单又换来了高效性和高可靠性。
二、SQLite的主要优点:1. 一致性的文件格式:在SQLite的官方文档中是这样解释的,我们不要将SQLite与Oracle或PostgreSQL去比较,而是应该将它看做fopen和fwrite。
与我们自定义格式的数据文件相比,SQLite不仅提供了很好的移植性,如大端小端、32/64位等平台相关问题,而且还提供了数据访问的高效性,如基于某些信息建立索引,从而提高访问或排序该类数据的性能,SQLite提供的事务功能,也是在操作普通文件时无法有效保证的。
2. 在嵌入式或移动设备上的应用:由于SQLite在运行时占用的资源较少,而且无需任何管理开销,因此对于PDA、智能手机等移动设备来说,SQLite的优势毋庸置疑。
3. 内部数据库:在有些应用场景中,我们需要为插入到数据库服务器中的数据进行数据过滤或数据清理,以保证最终插入到数据库服务器中的数据有效性。
SQLite数据库_计算机软件及应用_IT计算机_专业资料

Android SQLite数据库增删改查操作的使用详解一、使用嵌入式关系型SQLite数据库存储数据在Android平台上,集成了一个嵌入式关系型数据库——SQLite,SQLite3支持NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。
SQLite最大的特点是你可以把各种类型的数据保存到任何字段中,而不用关心字段声明的数据类型是什么。
例如:可以在Integer类型的字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。
但有一种情况例外:定义为I NTEGER PRIMARY KEY的字段只能存储64位整数,当向这种字段保存除整数以外的数据时,将会产生错误。
另外,在编写CREATE TABLE 语句时,你可以省略跟在字段名称后面的数据类型信息,如下面语句你可以省略name字段的类型信息:CREATE TABLE person (personid integer primary key autoincrement, name varchar(20)) SQLite可以解析大部分标准SQL语句,如:代码如下:创建数据库有两种方式:1.使用SQLiteDatabase的静态方法创建或打开数据库->static SQLiteDatabase openDatabase(Stringpath,SQLiteDatabase.CursorFactory factory,int flag): 打开path文件所代表的SQLite数据库。
->static SQLiteDatabase openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory factory): 打开或创建(如果不存在)file文件所代表的SQLite数据库。
SQLite的介绍操作Sqlite具体实例

SQLite的介绍操作Sqlite具体实例1.SQLite简介SQLite是⼀款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计⽬标是嵌⼊式的,⽽且⽬前已经在很多嵌⼊式产品中使⽤了它,它占⽤资源⾮常的低,在嵌⼊式设备中,可能只需要⼏百K的内存就够了。
它能够⽀持 Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语⾔相结合,⽐如Tcl、PHP、Java、C++、.Net等,还有ODBC接⼝,同样⽐起 Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度⽐他们都快。
2.SQLite的特点:轻量级SQLite和C/S模式的数据库软件不同,它是进程内的数据库引擎,因此不存在数据库的客户端和服务器。
使⽤SQLite⼀般只需要带上它的⼀个动态库,就可以享受它的全部功能。
⽽且那个动态库的尺⼨也挺⼩,以版本3.6.11为例,Windows下487KB、Linux下347KB。
不需要"安装"SQLite的核⼼引擎本⾝不依赖第三⽅的软件,使⽤它也不需要"安装"。
有点类似那种绿⾊软件。
单⼀⽂件数据库中所有的信息(⽐如表、视图等)都包含在⼀个⽂件内。
这个⽂件可以⾃由复制到其它⽬录或其它机器上。
跨平台/可移植性除了主流操作系统 windows,linux之后,SQLite还⽀持其它⼀些不常⽤的操作系统。
弱类型的字段同⼀列中的数据可以是不同类型开源3.SQLite数据类型⼀般数据采⽤的固定的静态数据类型,⽽SQLite采⽤的是动态数据类型,会根据存⼊值⾃动判断。
SQLite具有以下五种常⽤的数据类型:NULL: 这个值为空值VARCHAR(n):长度不固定且其最⼤长度为 n 的字串,n不能超过 4000。
CHAR(n):长度固定为n的字串,n不能超过 254。
INTEGER: 值被标识为整数,依据值的⼤⼩可以依次被存储为1,2,3,4,5,6,7,8.REAL: 所有值都是浮动的数值,被存储为8字节的IEEE浮动标记序号.TEXT: 值为⽂本字符串,使⽤数据库编码存储(TUTF-8, UTF-16BE or UTF-16-LE).BLOB: 值是BLOB数据块,以输⼊的数据格式进⾏存储。
sqlite 用法

sqlite 用法SQLite是一种轻型关系型数据库管理系统,它是一个C语言库,实现了自给自足、无服务器、零配置、事务性的SQL数据库引擎。
SQLite不需要单独的服务器进程或操作系统支持,这使它成为嵌入式数据库的理想选择,也适用于客户端/服务器的数据库应用程序。
SQLite的文件格式跨平台,可以在不同的操作系统中共享。
SQLite 的应用非常广泛,包括Android、iOS、Windows、Linux等系统中的各种应用程序和网站。
SQLite的使用非常简单,只需要引入SQLite的头文件,然后使用相应的API即可实现数据库的连接、数据的插入、查询、更新和删除等操作。
SQLite的API包含在sqlite3.h头文件中,其中最常用的API包括:sqlite3_open()用于连接数据库,sqlite3_exec()用于执行SQL语句,sqlite3_prepare_v2()用于准备SQL语句,sqlite3_step()用于执行SQL语句的下一步,sqlite3_finalize()用于释放已准备好的SQL语句,sqlite3_close()用于关闭数据库连接等。
在SQLite中,数据存储在表中,每个表由一组列组成。
表的创建可以使用SQL语句CREATE TABLE,格式为:CREATE TABLE 表名 (列1名列1类型, 列2名列2类型, …) 例如:CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)这个语句创建了一个名为“user”的表,包含三列:id、name和age。
其中,id列为主键,类型为INTEGER,name列和age列分别为TEXT和INTEGER类型。
表的数据可以通过INSERT INTO语句进行插入,例如:INSERT INTO user (name, age) VALUES ('Tom', 20) 这个语句向user表中插入了一条记录,name列的值为“Tom”,age列的值为20。
sqlite 指南pdf

sqlite 指南SQLite是一个C库,实现了轻量级的关系型数据库系统。
以下是SQLite的指南:1. 安装:首先需要下载并安装SQLite库。
可以从SQLite官网下载最新版本的SQLite源代码,并按照说明进行编译和安装。
2. 创建数据库:使用sqlite3命令行工具可以创建一个新的数据库文件。
例如,在命令行中输入“sqlite3 mydatabase.db”将创建一个名为“mydatabase.db”的数据库文件。
3. 创建表:在SQLite中,可以使用CREATE TABLE语句创建表。
例如,“CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);”将创建一个名为“mytable”的表,包含id、name和age 三个字段。
4. 插入数据:可以使用INSERT INTO语句向表中插入数据。
例如,“INSERT INTO mytable (name, age) VALUES ('John', 25);”将在“mytable”表中插入一条记录,包含name和age两个字段的值。
5. 查询数据:可以使用SELECT语句查询表中的数据。
例如,“SELECT * FROM mytable WHERE age > 20;”将查询“mytable”表中年龄大于20的所有记录。
6. 更新数据:可以使用UPDATE语句更新表中的数据。
例如,“UPDATE mytable SET age = 30 WHERE name = 'John';”将更新“mytable”表中name字段为“John”的记录的age字段为30。
7. 删除数据:可以使用DELETE语句删除表中的数据。
例如,“DELETE FROM mytable WHERE name = 'John';”将删除“mytable”表中name字段为“John”的所有记录。
sqllite使用说明

sqllite使用说明SQLite是一种轻量级的关系型数据库管理系统,它被广泛应用于移动设备、嵌入式系统以及小型应用程序中。
下面我将从安装、创建数据库、创建表、插入数据、查询数据和更新数据等方面为你介绍SQLite的使用说明。
首先,要使用SQLite,你需要安装SQLite的数据库引擎。
SQLite数据库引擎是一个独立的C库,可以通过官方网站或者其他渠道下载安装。
安装完成后,你就可以开始创建和管理SQLite数据库了。
接下来是创建数据库。
你可以使用命令行工具或者SQLite的客户端应用程序来创建数据库。
在命令行中,你可以通过输入命令"sqlite3 yourdatabasename.db"来创建一个名为yourdatabasename.db的数据库文件。
在客户端应用程序中,一般会有相应的界面操作来创建数据库。
创建数据库后,你可以开始创建表。
使用SQL语句来创建表,例如,"CREATE TABLE tablename (column1 datatype, column2 datatype, column3 datatype, ...);"。
这样就可以创建一个名为tablename的表,并定义了列名和数据类型。
接着是插入数据。
使用SQL语句"INSERT INTO tablename (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);"来向表中插入数据。
这样就可以将指定的数值插入到对应的列中。
然后是查询数据。
使用SQL语句"SELECT column1,column2, ... FROM tablename WHERE condition;"来查询数据。
这样就可以从表中检索出符合条件的数据,并返回指定的列。
最后是更新数据。
使用SQL语句"UPDATE tablename SET column1 = value1, column2 = value2 WHERE condition;"来更新数据。
sqlite 基本操作

sqlite 基本操作SQLite是一种轻量级的关系型数据库管理系统,它提供了一套简单易用的操作接口,使得开发者可以方便地进行数据库的创建、查询、更新和删除等基本操作。
本文将介绍SQLite的基本操作,包括数据库的创建与连接、表的创建与删除、数据的插入与查询、数据的更新与删除等内容。
一、数据库的创建与连接1. 创建数据库:使用SQLite提供的命令或者API,可以创建一个新的数据库文件。
可以指定数据库文件的路径和名称,也可以使用默认的名称。
2. 连接数据库:连接数据库是指在应用程序中与数据库建立起通信的通道。
通过连接数据库,可以执行后续的操作,包括创建表、插入数据、查询数据等。
二、表的创建与删除1. 创建表:在数据库中,表是用于存储数据的结构化对象。
通过使用SQLite提供的命令或者API,可以创建一个新的表。
在创建表时,需要指定表的名称和表的字段,以及每个字段的类型和约束。
2. 删除表:当不再需要某个表时,可以使用SQLite提供的命令或者API,将其从数据库中删除。
删除表的操作将会删除表中的所有数据,因此在执行删除操作前应慎重考虑。
三、数据的插入与查询1. 插入数据:在已创建的表中,可以通过使用SQLite提供的命令或者API,向表中插入新的数据。
插入数据时,需要指定数据要插入的表和字段,以及每个字段对应的值。
2. 查询数据:查询数据是使用SQLite最常见的操作之一。
通过使用SQLite提供的命令或者API,可以从表中检索出满足特定条件的数据。
查询操作可以使用各种条件和操作符,以及排序和分组等功能。
四、数据的更新与删除1. 更新数据:在已有的表中,可以使用SQLite提供的命令或者API,更新表中的数据。
更新数据时,需要指定要更新的表和字段,以及每个字段对应的新值。
可以使用各种条件和操作符,以确定要更新的数据行。
2. 删除数据:删除数据是使用SQLite的另一个常见操作。
通过使用SQLite提供的命令或者API,可以从表中删除满足特定条件的数据。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验11SQLite数据库的使用一、实验目的1.掌握创建SQLite数据库的方法;2.掌握实现对SQLite数据增删改查的方法;3.学会使用adb调试工具查瞧数据库与数据表;二、知识要点1.创建SQLite数据库的方法:①定义一个帮助类MyHelper继承SQLiteOpentHelper类;②在MyHelper类中定义构造方法,重写onCreate()与onUpgrade()方法;③在onCreate(SQLiteDatabasedb)方法中,通过参数db调用execSQL(String sql)方法执行建表SQL语句;④创建一个MyHelper类对象helper,调用构造方法对其进行初始化,然后由helper对象调用getWritableDatabase()方法或getReadableDatabase()创建数据库。
2.实现SQLite数据增删改查的方法:(1)添加数据:①获取一个SQLiteDatabase对象db;②通过db对象调用以下任一方法实现数据添加:a)execSQL(String sql)方法执行insert SQL语句;如:db、execSQL(“insert into table_name(column_list) values(value_list)”);b)调用insert(表名,null,添加的数据values)方法:首先,定义一个ContentValues对象values,通过values对象调用put()方法将要添加的数据存入values对象,然后再通过db对象调用insert()方法,将values中的数据添加到指定的数据表中。
(2)更新数据:①获取一个SQLiteDatabase对象db;②通过db对象调用以下任一方法实现数据添加:a)execSQL(String sql)方法执行update SQL语句;如:db、execSQL(“update table_name set column=value,… where condition”);b)调用update(String table, ContentValuesvalues,StringwhereClause,String[] whereArgs)方法:首先,定义一个ContentValues对象values,通过values对象调用put()方法将要更新的数据存入values对象,然后再通过db对象调用update()方法,指定要修改数据的表名,更新的数据values,约束更新某一行火某几行中的数据。
(3)删除数据:①获取一个SQLiteDatabase对象db;②通过db对象调用以下任一方法实现数据添加:a)execSQL(String sql)方法执行delete SQL语句;如:db、execSQL(“delete from table_name where condition”);b)调用delete(String table, String whereClause,String[] whereArgs)方法,指定要删除数据的表名称,以及约束删除某一行或某几行中的数据。
(4)查询数据:①获取一个SQLiteDatabase对象db;②通过db对象调用query()方法,指定要查询的表名、列名、以及where约束条件等,并将查询结果存入一个Cursor对象中。
如:Cursor cursor=db、query(表名,列名,where约束条件,为where中的占位符提供具体的,null,null,null);三、实验内容1.创建一个Android项目,项目名称为“shiyan1101_专业_×××(学生姓名)”,要求:(1)自动创建Activity;(2)使用XML编写界面;(3)界面构成:①4个文本框,分别用来显示提示信息“图书名称”、“图书作者”、“图书价格”、“图书页数”;②4个编辑框,分别用来接收用户输入“图书名称”、“图书作者”、“图书价格”、“图书页数”;③5个按钮,文本显示分别为“创建SQLite数据库”、“添加数据”、“修改数据”、“删除数据”、“查询数据”。
(4)程序实现功能:①点击“创建SQLite数据库”按钮,创建一个SQLite数据库BookStore、db,并创建一个数据表Book,通过Toast显示“数据库BookStore、db创建成功!”,要求使用adb查瞧数据库创建就是否成功。
②点击“添加数据”按钮,将用户在编辑框中输入的图书名称、图书作者、图书价格、图书页数等数据写入添加到数据表Book中。
③点击“修改数据”按钮,将数据表Book中指定的数据进行修改,条件根据题目自己设定。
④点击“删除数据”按钮,将数据表Book中指定的数据删除,删除条件根据题目自己设定。
⑤点击“查询数据”按钮,查询数据表Book中指定的数据,将查询结果通过Log显示。
(5)实验报告中要求用语言描述具体的实验步骤,并附以截图做辅助说明。
【具体过程参见课件——第3部分数据存储中的练习2-6。
】Mydatebase,javapublic class Mydatebase extends SQLiteOpenHelper {public static final String cerat= "create table if not exists book( _id integer primary key autoincrement, " +"name text,zuozhe text ,price real,page integer );";public Mydatebase(Context context, String name, CursorFactory factory, int version) {super(context, name, factory, version);// TODO Auto-generated constructor stub}@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubdb、execSQL( cerat);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub}}创建数据库按钮protected void onCreate(Bundle savedInstanceState) {super、onCreate(savedInstanceState);setContentView(R、layout、activity_main);mydb=new Mydatebase(MainActivity、this, "BookStore、db", null, 1);btcreat=(Button)findViewById(R、id、create);btcreat、setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubdb=mydb、getWritableDatabase();//db、execSQL(INSERT_DATA);db、execSQL("insert into book (name,zuozhe,price,page)" +"Values('dnjkc','fdg',35、0,123)");}});添加数据按钮edname=(EditText)findViewById(R、id、ed1);edau=(EditText)findViewById(R、id、ed2);edjiage=(EditText)findViewById(R、id、ed3);edpage=(EditText)findViewById(R、id、ed4);btadd=(Button)findViewById(R、id、add);btadd、setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString sname=edname、getText()、toString();String sau=edau、getText()、toString();Double djiage=Double、parseDouble(edjiage、getText()、toString());int ipage=Integer、parseInt(edpage、getText()、toString());ContentValues values=new ContentValues();values、put("name", sname);values、put("zuozhe",sau);values、put("price", djiage);values、put("page", ipage);SQLiteDatabase db=mydb、getWritableDatabase();db、insert("book", null, values);}});}修改数据按钮btgai=(Button)findViewById(R、id、xiu);btgai、setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubSQLiteDatabase db=mydb、getWritableDatabase();db、execSQL("update book set name='孙孟也' where name='smy';");}});}删除数据按钮btdelete=(Button)findViewById(R、id、delete);btdelete、setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubSQLiteDatabase db=mydb、getWritableDatabase();db、execSQL("delete from book where name='孙孟也'");}});查询数据按钮btcha=(Button)findViewById(R、id、select);btcha、setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubSQLiteDatabase db=mydb、getWritableDatabase();//查询Book表中所有的数据Cursor cursor=db、query("Book", null, null, null, null, null, null);if(cursor、moveToFirst()){do{//遍历cursor对象,取出数据并打印String name=cursor、getString(cursor、getColumnIndex("name"));String author=cursor、getString(cursor、getColumnIndex("zuozhe"));double price=cursor、getDouble(cursor、getColumnIndex("price"));int pages=cursor、getInt(cursor、getColumnIndex("page"));Log、d("Message","book name is"+name);Log、d("Message","book author is"+author);Log、d("Message","book price is"+price);Log、d("Message","book pages is"+pages);}while(cursor、moveToNext());}cursor、close();}});}。