android中使用sqlite
android sqlite3 sql select 用法

android sqlite3 sql select 用法
在 Android 开发中,可以使用 SQLite3 数据库,并通过 SQL 的`SELECT`语句来从数据库中获取数据。
以下是`SELECT`语句的基本用法:
```sql
SELECT column1, column2, ...
FROM table_name
WHERE condition;
```
其中:
- `column1, column2, ...`是你想要选择的列名,可以指定一个或多个列,用逗号分隔。
- `table_name`是要从中选择数据的表名。
- `WHERE condition`是可选的条件,用于筛选结果。
如果省略,则将返回表中的所有行。
例如,以下是一个简单的示例,选择名为`students`表中的所有列:
```sql
SELECT * FROM students;
```
如果你只想选择特定的列,可以这样做:
```sql
SELECT name, age FROM students;
```
还可以使用`WHERE`子句来添加条件:
```sql
SELECT * FROM students WHERE age > 18;
```
这将返回`students`表中`age`列大于 18 的所有行。
你可以根据自己的需求进行组合和扩展这些查询语句。
请注意,在实际使用中,还需要
考虑适当的错误处理和数据库操作的封装。
安卓sqlite常用语句

SQLite 是Android 平台上的默认数据库管理系统,用于存储和检索数据。
以下是一些常用的SQLite 语句和操作:1. 创建数据库:sqlCREATE DATABASE [database_name];2. 打开数据库:如果你想在特定数据库上执行操作,你需要先打开它。
sqlATTACH DATABASE [database_name] AS [database_alias];3. 创建表:sqlCREATE TABLE [table_name] ([column1] [data_type],[column2] [data_type],...);4. 插入数据:sqlINSERT INTO [table_name] ([column1], [column2], ...)VALUES ([value1], [value2], ...);5. 查询数据:sqlSELECT FROM [table_name]; -- 选择所有列SELECT [column1], [column2] FROM [table_name]; -- 选择特定列6. 更新数据:sqlUPDATE [table_name]SET [column1] = [value1], [column2] = [value2], ...WHERE [condition];7. 删除数据:sqlDELETE FROM [table_name] WHERE [condition];8. 创建索引:创建索引可以加速查询速度。
sqlCREATE INDEX [index_name] ON [table_name] ([column1], [column2], ...);9. 创建触发器:触发器是与特定表相关联的特殊类型的存储过程,它自动执行特定操作。
例如,当向表中插入、更新或删除记录时,触发器可以自动执行。
10. 创建视图:视图是基于一个或多个表的虚拟表。
android之sqlite实现增删改查

Sqlite 实现简单的增删改查主界面:功能实现:1)增加数据:2)全部显示3)清除显示4)全部删除5):ID删除6)ID查询:7)ID更新:主要代码段:DBOpenHelper.javapackage com.chen.dao;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public class DBOpenHelper extends SQLiteOpenHelper { private static final int VERSION=2;//版本private static final String DBNAME="user.db";//数据库名字//创建数据库public DBOpenHelper(Context context) {super(context, DBNAME, null, VERSION);}@Override/** 创建表*/public void onCreate(SQLiteDatabase db) {db.execSQL("create table if not exists u_user(_id integer primary key,name varchar(20),age integer,tall varchar(5))");}//版本被更新时执行@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}UserDAO.javapackage com.chen.dao;import java.util.ArrayList;import java.util.List;import er;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;public class UserDAO {private DBOpenHelper helper;//写入,不然会是出错,是空指针public UserDAO(Context context){helper=new DBOpenHelper(context);}/*** 添加用户信息*/public void add(User user){SQLiteDatabase db=helper.getWritableDatabase();String sql="Insert into u_user(_id,name,age,tall) values(?,?,?,?)";db.execSQL(sql, new Object[]{user.getId(),user.getName(),user.getAge(),user.getTall()});db.close();}/*** 删除用户信息*/public void delete(Integer...id){if(id.length>0){StringBuffer sb=new StringBuffer();for(int i=0;i<id.length;i++){sb.append("?").append(",");}sb.deleteCharAt(sb.length()-1);SQLiteDatabase database=helper.getWritableDatabase();String sql="delete from u_user where _id in ("+sb+")";database.execSQL(sql, (Object[])id);}}/*** 删除表里的全部数据*/public void delelteall(){SQLiteDatabase database=helper.getWritableDatabase();String sql = "delete from u_user";database.execSQL(sql);}/*** 用户修改*/public void update(User user){SQLiteDatabase db=helper.getWritableDatabase();//写入数据库中注意!!!!不能放在外面String sql="update u_user set name=?,age=?,tall=? where _id=?";db.execSQL(sql, new Object[]{user.getName(),user.getAge(),user.getTall(),user.getId()});}/*** 查找用户信息*/public User find(int userid){SQLiteDatabase db=helper.getWritableDatabase();//写入数据库中注意!!!!不能放在外面String sql="select _id,name,age,tall from u_user where _id=?";Cursor cursor=db.rawQuery(sql, new String[]{String.valueOf(userid)});if(cursor.moveToNext()){return new User(cursor.getInt(cursor.getColumnIndex("_id")),cursor.getString(cursor.getColumnIndex("name")),cursor.getInt(cursor.getColumnIndex("age")),cursor.getString(cursor.getColumnIndex("tall")));}return null;}/*** 显示用户*/public Cursor select() {SQLiteDatabase db = helper.getReadableDatabase();Cursor cursor = db.query("u_user",null, null, null, null,null, "_id desc");return cursor;}}MainActivity.javapackage com.chen.database;/*** writer:ManMan*Email:*******************/import erDAO;import er;import android.app.Activity;import android.database.Cursor;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.SimpleCursorAdapter;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener{ private static final String TAG = "Add";private EditText edname,edage,edtall,id;private Button add,deleteshow,show,iddelete,idupdate,idshow,deleteall;private TextView tedatashow;private ListView datashow;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);edname = (EditText)findViewById(R.id.edname);edage = (EditText)findViewById(R.id.edage);edtall = (EditText)findViewById(R.id.edtall);id = (EditText)findViewById(R.id.id);tedatashow = (TextView)findViewById(R.id.tedatashow);datashow = (ListView)findViewById(R.id.datashow);add = (Button)findViewById(R.id.add);deleteshow = (Button)findViewById(R.id.deleteshow);show = (Button)findViewById(R.id.show);iddelete = (Button)findViewById(R.id.iddelete);idupdate = (Button)findViewById(R.id.idupdate);idshow = (Button)findViewById(R.id.idshow);deleteall = (Button)findViewById(R.id.deleteall);add.setOnClickListener(this);deleteshow.setOnClickListener(this);show.setOnClickListener(this);iddelete.setOnClickListener(this);idupdate.setOnClickListener(this);idshow.setOnClickListener(this);deleteall.setOnClickListener(this);}public void onClick(View v) {/** 添加数据*/if(v==add){if(!id.getText().toString().equals(null)&&!edname.getText().toString().equals(null)&&!edage .getText().toString().equals(null)&&!edtall.getText().toString().equals(null)){try{UserDAO userdao = new UserDAO(MainActivity.this);User user = new User(Integer.valueOf(id.getText().toString()), edname.getText().toString(),Integer.valueOf(edage.getText().toString()), edtall.getText().toString());userdao.add(user);Toast.makeText(MainActivity.this, "成功添加!", Toast.LENGTH_LONG).show();tedatashow.setText("新添数据为:"+"\n"+"ID:"+Integer.valueOf(id.getText().toString())+","+"姓名:"+edname.getText().toString()+","+"年龄:"+Integer.valueOf(edage.getText().toString())+","+"身高:"+edtall.getText().toString()+",");//设置为空edage.setText("");edname.setText("");edtall.setText("");id.setText("");}catch (Exception e) {Log.i(TAG, "出错了");Log.i(TAG, e.getMessage());}}else if(id.getText().toString().equals(null)){Toast.makeText(MainActivity.this, "ID不能为空!", Toast.LENGTH_LONG) .show();}}/** 清除显示*/if(v==deleteshow){tedatashow.setText("");}/** 全部显示*/if(v==show){try{UserDAO userdao = new UserDAO(MainActivity.this);Cursor cursor = userdao.select();/** 构建Listview适配器*/SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, yout.showuser, cursor, new String[]{"_id","name","age","tall" },newint[]{R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4});datashow.setAdapter(adapter);}catch (Exception f) {Log.e("err",f.getMessage());Log.e("err",null, f.getCause());Toast.makeText(MainActivity.this, "显示不了", Toast.LENGTH_LONG).show();}}/** ID删除*/if(v==iddelete){UserDAO userDAO=new UserDAO(MainActivity.this);//注意不能放在外面userDAO.delete(Integer.valueOf(id.getText().toString()));Toast.makeText(MainActivity.this, "您成功删除了"+Integer.valueOf(id.getText().toString()), Toast.LENGTH_LONG).show();id.setText("");}/** 全部删除*/if(v==deleteall){UserDAO userDAO=new UserDAO(MainActivity.this);//注意不能放在外面userDAO.delelteall();Toast.makeText(MainActivity.this, "您已经把数据全部删除了", Toast.LENGTH_LONG).show();}/** ID更新*/if(v==idupdate){UserDAO userDAO=new UserDAO(MainActivity.this);//注意不能放在外面User user=userDAO.find(Integer.valueOf(id.getText().toString()));user.setName(edname.getText().toString());user.setAge(Integer.valueOf(edage.getText().toString()));user.setTall(edtall.getText().toString());userDAO.update(user);Toast.makeText(MainActivity.this, "修改成功", Toast.LENGTH_LONG).show();}/** ID查询*/if(v==idshow){UserDAO userDAO=new UserDAO(MainActivity.this);//注意不能放在外面User user=userDAO.find(Integer.valueOf(id.getText().toString()));tedatashow.setText("ID:"+user.getId()+" "+"姓名:"+user.getName()+" "+"年龄:"+user.getAge()+" "+"身高"+user.getTall());}/***/}}User.javapackage com.chen.modl;public class User {private int id;private String name;private int age;private String tall;/** 构造方法*/public User(){super();}public User(int id,String name,int age,String tall){ this.id=id;=name;this.age=age;this.tall=tall;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) { = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getTall() {return tall;}public void setTall(String tall) {this.tall = tall;}//复写toString()方法进行查找public String toString(){return"id:"+id+"name:"+name+"age"+age+"tall"+tall;}}Main.xml<?xml version="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><LinearLayoutandroid:orientation="horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"><!--姓名 --><TextViewandroid:text="姓名:"android:layout_width="wrap_content"android:layout_height="wrap_content"/><EditTextandroid:id="@+id/edname"android:layout_height="wrap_content"android:layout_width="278dp"/></LinearLayout><LinearLayoutandroid:orientation="horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"><!--年龄 --><TextViewandroid:text="年龄:"android:layout_width="wrap_content"android:layout_height="wrap_content"/><EditTextandroid:id="@+id/edage"android:layout_width="278dp"/></LinearLayout><!--身高 --><LinearLayoutandroid:orientation="horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content" ><TextViewandroid:text="身高:"android:layout_width="wrap_content"android:layout_height="wrap_content" /><EditTextandroid:id="@+id/edtall"android:layout_height="wrap_content"android:layout_width="278dp"/></LinearLayout><!--按钮 --><LinearLayoutandroid:orientation="horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content" ><Buttonandroid:id="@+id/add"android:text="添加数据"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="3dip"/><Buttonandroid:id="@+id/show"android:text="全部显示"android:layout_width="wrap_content"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/deleteshow"android:text="清除显示"android:layout_width="wrap_content"/><Buttonandroid:id="@+id/deleteall"android:text="全部删除"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout><!--按钮 --><LinearLayoutandroid:orientation="horizontal"android:layout_width="wrap_content"android:layout_height="wrap_content"><TextViewandroid:text="ID:"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="3dip"android:layout_weight="1"/><EditTextandroid:id="@+id/id"android:layout_width="75dip"android:layout_height="wrap_content"android:layout_marginLeft="3dip"android:layout_weight="2"/><Buttonandroid:id="@+id/iddelete"android:text="ID删除"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="5dip"android:layout_weight="1"/><Buttonandroid:id="@+id/idshow"android:text="ID查询"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"/><Buttonandroid:id="@+id/idupdate"android:text="ID更新"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"/></LinearLayout><TextViewandroid:text="数据库数据显示:"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/tedatashow"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textSize="15dip"/><ListViewandroid:id="@+id/datashow"android:layout_width="fill_parent"android:layout_height="wrap_content"android:textSize="15dip"/></LinearLayout>。
android中SQLite的使用总结,用excSQL和rawQuery方法实现一般得增删改查

android中SQLite的使用总结,用excSQL和rawQuery方法实现一般得增删改查1:androidmanifest.xml的内容[html]view plaincopy1.<?xml version="1.0" encoding="utf-8"?>2.<manifest xmlns:android="/apk/res/android"3.package="cn.itcast.db"4.android:versionCode="1"5.android:versionName="1.0">6.<application android:icon="@drawable/icon" android:lab el="@string/app_name">7.<uses-library android:name="android.test.runner" />8.<activity android:name=".MainActivity"9.android:label="@string/app_name">10.<intent-filter>11.<action android:name="android.intent.action.MAIN" / >12.<category android:name=" UNCHER" />13.</intent-filter>14.</activity>15.16.</application>17.18.<uses-sdk android:minSdkVersion="8" />19.<!-- 配置测试环境 -->20.<instrumentation android:name="android.test.Instru mentationTestRunner"21.android:targetPackage="cn.itcast.db"22.android:label="T est for My App"/>23.24.</manifest>2:Person类[java]view plaincopy1.package cn.itcast.domain;2.3.public class Person {4.5.private Integer id;6.private String name;7.8.public Person() {9.10.}11.12.public Integer getId() {13.return id;14.}15.16.public void setId(Integer id) {17.this.id = id;18.}19.20.public String getName() {21.return name;22.}23.24.public void setName(String name) { = name;26.}27.28.@Override29.public String toString() {30.return "Person [id=" + id + ", name=" + name + "]";31.}32.33.}3:DBOpenHelper类,该类继承了SQLiteOpenHelper类[java]view plaincopy1.package cn.itcast.service;2.3.import android.content.Context;4.import android.database.sqlite.SQLiteDatabase;5.import android.database.sqlite.SQLiteOpenHelper;6.import android.database.sqlite.SQLiteDatabase.CursorFac tory;7.8.public class DBOpenHelper extends SQLiteOpenHelper {9.10.private static final String DATABASENAME = "cn.itcast. db";11.private static final int DATABASEVERSION = 1;12.13./*14.* 构造函数15.*/16.public DBOpenHelper(Context context) {17.super(context, DATABASENAME, null, DATABASEVERSION);18.}19.20./*21.* 数据库第一次生成时调用该方法,创建一些表或者初始化一些数据22.* @see android.database.sqlite.SQLiteOpenHelper#on Create(android.database.sqlite.SQLiteDatabase)23.*/24.@Override25.public void onCreate(SQLiteDatabase db) {26.db.execSQL("create table person(personid integer pri mary key autoincrement, name varchar(20))");27.}28.29.@Override30.public void onUpgrade(SQLiteDatabase db, int oldVer sion, int newVersion) {31.32.}33.34.}4:PersonService类[java]view plaincopy1.package cn.itcast.service;2.3.import java.util.ArrayList;4.import java.util.List;5.6.import android.content.Context;7.import android.database.Cursor;8.import android.database.sqlite.SQLiteDatabase;9.import cn.itcast.domain.Person;10.11.public class PersonService {12.13.private DBOpenHelper dbOpenHelper;14.15.public PersonService(Context context) {16.this.dbOpenHelper = new DBOpenHelper(context);17.}18.19./*20.* save a person to the database21.*/22.public void save(Person person) {23.SQLiteDatabase database = dbOpenHelper.getWritabl eDatabase();24.database.execSQL("insert into person(name) values (?) ", new Object[]{person.getName()});25.}26.27./*28.* updata a person to the database29.*/30.public void update(Person person) {31.SQLiteDatabase database = dbOpenHelper.getWritabl eDatabase();32.database.execSQL("update person set name=? wherepersonid=?", new Object[]{person.getName(), person.getId()});33.}34.35./*36.* delete a person from the database according to the id37.*/38.public void delete(Integer id) {39.SQLiteDatabase database = dbOpenHelper.getWritabl eDatabase();40.database.execSQL("delete from person where personi d=?", new Object[]{id.toString()});41.}42.43./*44.* find a person from the database according to the id45.*/46.public Person find(Integer id) {47.SQLiteDatabase database = dbOpenHelper.getReadab leDatabase();48.Cursor cursor = database.rawQuery("select * from per son where personid=?", new String[]{id.toString()});49.Person person = null;50.if(cursor.moveT oFirst()) {51.Integer personid = cursor.getInt(cursor.getColumnInd ex("personid"));52.String name = cursor.getString(cursor.getColumnIndex ("name"));53.person = new Person();54.person.setId(personid);56.}57.return person;58.}59.60./*61.* get the data of person accroding to the offset and m axResult62.*/63.public List<Person> getScrollData(Integer offset, Integ er maxResult) {64.SQLiteDatabase database = dbOpenHelper.getReadab leDatabase();65.Cursor cursor = database.rawQuery("select * from per son limit ?,?", new String[] {offset.toString(), maxResult.toString() });66.int idIndex = 0;67.int nameIndex = 0;68.List<Person> personList = null;69.70.if(cursor.getCount() >= 0) {71.idIndex = cursor.getColumnIndex("personid");Index = cursor.getColumnIndex("name");73.personList = new ArrayList<Person>();74.}75.76.while(cursor.moveToNext()) {77.Integer personid = cursor.getInt(idIndex);78.String name = cursor.getString(nameIndex);79.Person person = new Person();81.person.setName(name);82.personList.add(person);83.}84.return personList;85.}86.87./*88.* get the count of the database89.*/90.public long getCount(){91.SQLiteDatabase database = dbOpenHelper.getReadab leDatabase();92.Cursor cursor = database.rawQuery("select count(*) fr om person", null);93.cursor.moveToFirst();94.return cursor.getLong(0);95.}96.97.}5:PersonServiceT est类[java]view plaincopy1.package cn.itcast.db;2.3.import java.util.List;4.5.import android.test.AndroidTestCase;6.import android.util.Log;7.import cn.itcast.domain.Person;8.import cn.itcast.service.DBOpenHelper;9.import cn.itcast.service.PersonService;10.11.public class PersonServiceTest extends AndroidT estCase {12.private static final String TAG = "PersonServiceTest";13.14./*15.* 测试生成数据库的方法16.*/17.public void testCreateDB() throws Throwable {18.DBOpenHelper dbOpenHelper = new DBOpenHelper( this.getContext());19.dbOpenHelper.getWritableDatabase(); //第一次调用该方法会生成数据库20.21.}22.23./*24.* 测试保存方法25.*/26.public void testSave() throws Throwable{27.PersonService personService = new PersonService(this .getContext());28.29.Person person1 = new Person();30.person1.setName("zhangsan");31.personService.save(person1);32.33.Person person2 = new Person();34.person2.setName("lisi");35.personService.save(person2);36.37.Person person3 = new Person();38.person3.setName("wangwu");39.personService.save(person3);40.41.}42.43.public void testDelete() {44.PersonService personService = new PersonService(this .getContext());45.personService.delete(1);46.47.}48.49./*50.* 测试更新方法51.*/52.public void testUpdate() {53.PersonService personService = new PersonService(this .getContext());54.Person person = personService.find(1);55.person.setName("zhaoliu");56.personService.update(person);57.58.}59.60./*61.* 测试获得数据方法63.public void testGetScrollData() throws Throwable{64.PersonService personService = new PersonService(this .getContext());65.List<Person> persons = personService.getScrollData(0 , 3);66.for(Person person : persons) {67.Log.i(TAG, person.toString());68.}69.}70.71./*72.* 测试根据id查找的方法73.*/74.public void testFind() throws Throwable{75.PersonService personService = new PersonService(this .getContext());76.Person person = personService.find(1);77.Log.i(TAG, person.toString());78.79.}80.81./*82.* 测试获得数量的方法83.*/84.public void testGetCount() {85.PersonService personService = new PersonService(this .getContext());86.long count = personService.getCount();87.Log.i(TAG, count + "");89.}。
Android学习之SQLite数据库存储

Android 学习之SQLite 数据库存储•引⾔概念 SQLite 数据库,和其他的SQL 数据库不同, 我们并不需要在⼿机上另外安装⼀个数据库软件,Android 系统已经集成了这个数据库;特点SQLite 是⼀个轻量级的关系型数据库,运算速度快,占⽤资源少,很适合在移动设备上使⽤不仅⽀持标准SQL 语法,还遵循ACID(数据库事务)原则,⽆需账号,使⽤起来⾮常⽅便SQLite ⽀持五种数据类型NULLinteger (整型)real(浮点型)text(⽂本类型)blob(⼆进制类型)SQLite 通过⽂件来保存数据库⼀个⽂件就是⼀个数据库数据库中⼜包含多个表格表格⾥⼜有多条记录每条记录由多个字段构成每个字段都有对应的值•创建数据库 Android 为了让我们能够更加⽅便地管理数据库,专门提供了⼀个 SQLiteOpenHelper 帮助类; 借助这个类就可以⾮常简单地对数据库进⾏创建和升级。
SQLiteOpenHelper 是⼀个抽象类,这意味着如果我们想要使⽤它的话,就需要创建⼀个⾃⼰的帮助类去继承它; SQLiteOpenHelper 中有两个抽象⽅法,分别是 和 ;: 数据库第⼀次被创建时被调⽤: 在数据库的版本发⽣变化时会被调⽤⼀般在软件升级时才需改变版本号,⽽数据库的版本是由程序员控制的假设数据库现在的版本是 1,由于业务的变更,修改了数据库表结构,这时候就需要升级软件,升级软件时希望更新⽤户⼿机⾥的数据库表结构为了实现这⼀⽬的,可以把原来的数据库版本设置为 2,或者其他与旧版本号不同的数字即可 我们必须在⾃⼰的帮助类⾥⾯重写这两个⽅法,然后分别在这两个⽅法中去实现 创建、升级数据库 的逻辑。
SQLiteOpenHelper 中还有两个⾮常重要的实例⽅法: 和 。
这两个⽅法都可以 创建或打开 ⼀个现有的数据库(如果数据库已存在则直接打开,否则创建⼀个新的数据库), 并返回⼀个可对数据库进⾏读写操作的对象。
在Android应用中利用SQLite进行本地数据库操作

在Android应用中利用SQLite进行本地数据库操作随着移动应用的不断发展,电子设备成为人们生活中不可或缺的一部分。
而Android操作系统作为最广泛使用的移动操作系统之一,它提供了强大的开发平台,为开发者们提供了各种各样的开发工具和API。
其中,SQLite作为Android应用中的一种轻量级数据库管理系统,被广泛应用于数据存储和管理。
本文将介绍在Android应用中通过SQLite实现本地数据库操作的方法。
1. 简介SQLite是一种无服务器的自包含的数据库引擎,它在Android操作系统中作为默认的关系型数据库引擎。
它无需独立的服务器进程,将数据库引擎与应用程序合并在一起,使得应用程序可以直接操作数据库。
SQLite在移动设备上非常流行,因为它占用的磁盘空间相对较少,并且提供了性能高效的操作方式。
2. 创建数据库在Android应用中使用SQLite进行本地数据库操作,首先需要创建一个数据库。
Android提供了SQLiteOpenHelper类来管理数据库的创建和升级。
在创建数据库之前,首先需要定义数据库的结构,包括表的结构和字段信息。
接着,通过继承SQLiteOpenHelper类,重写onCreate()方法和onUpgrade()方法,可以自动创建数据库和升级数据库。
3. 创建表使用SQLite进行本地数据库操作时,需要在数据库中创建表来存储数据。
通过执行SQL语句,可以在数据库中创建表以及定义表中的字段信息。
SQLite支持多种数据类型,包括整型、浮点型、文本型等。
通过在SQL语句中指定字段的名称和类型,可以创建适合应用需求的表。
4. 插入数据插入数据是在数据库中进行本地数据库操作的常见操作之一。
通过执行SQL 语句的INSERT INTO语句,可以将数据插入到数据库的表中。
通过使用ContentValues类,可以方便地设置插入数据的字段值。
通过调用SQLiteDatabase 类的insert()方法,可以执行插入数据的操作。
android sqlite query方法

android sqlite query方法在Android开发中,使用SQLite数据库进行查询是一个常见的操作。
下面是一个简单的例子,展示如何在Android中执行一个SQLite查询:1. 创建数据库助手类:首先,你需要创建一个帮助类来管理你的数据库。
这个类通常会包含创建数据库、打开数据库和执行查询的方法。
2. 定义表格:在数据库中定义一个表格。
例如,你可以创建一个名为`Users`的表格,其中包含`id`, `name`, 和`age`字段。
3. 执行查询:使用`SQLiteDatabase`的`query`方法来执行查询。
这个方法需要指定表名、列名、筛选条件等。
4. 处理结果:查询结果通常会返回一个`Cursor`对象。
你可以遍历这个对象来获取查询到的数据。
下面是一个示例代码,展示如何在Android中执行一个简单的SQLite查询:```javaimport ;import ;import ;import ;import ;public class DatabaseHelper extends SQLiteOpenHelper {private static final String DATABASE_NAME = "";private static final int DATABASE_VERSION = 1;private static final String TABLE_NAME = "Users";private static final String COLUMN_ID = "id";private static final String COLUMN_NAME = "name";private static final String COLUMN_AGE = "age";private static final String COLUMN_CREATED_AT = "created_at";public DatabaseHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION); }Overridepublic void onCreate(SQLiteDatabase db) {String createTableQuery = "CREATE TABLE " + TABLE_NAME + " (" +COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +COLUMN_NAME + " TEXT, " +COLUMN_AGE + " INTEGER, " +COLUMN_CREATED_AT + " DATETIME DEFAULT CURRENT_TIMESTAMP" +");";(createTableQuery);}Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {("DROP TABLE IF EXISTS " + TABLE_NAME);onCreate(db);}public void addUser(String name, int age) {SQLiteDatabase db = ();ContentValues contentValues = new ContentValues();(COLUMN_NAME, name);(COLUMN_AGE, age);(TABLE_NAME, null, contentValues);();}public Cursor getUsers() {SQLiteDatabase db = ();String selectQuery = "SELECT FROM " + TABLE_NAME;Cursor cursor = (TABLE_NAME, null, null, null, null, null, null); return cursor;}}```在上面的代码中,我们定义了一个`DatabaseHelper`类,它包含了创建数据库、添加用户和查询用户的方法。
android sqlite 插入数据的方法

android sqlite 插入数据的方法在 Android 中使用 SQLite 数据库进行数据插入的方法如下: 1. 创建一个继承自 `SQLiteOpenHelper` 的数据库辅助类,用于创建和管理数据库以及表结构。
在该类中,需要实现 `onCreate()` 方法来创建数据库和表,以及 `onUpgrade()` 方法来处理数据库版本升级。
```javapublic class DBHelper extends SQLiteOpenHelper {private static final String DATABASE_NAME = "mydatabase.db";private static final int DATABASE_VERSION = 1;public DBHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION); }@Overridepublic void onCreate(SQLiteDatabase db) {// 创建表结构String createTableQuery = "CREATE TABLE mytable (id INTEGER PRIMARY KEY, name TEXT)";db.execSQL(createTableQuery);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// 处理数据库版本升级if (oldVersion < 2) {// 执行相应的更新操作}}}```2. 在需要插入数据的地方,获取可写入的数据库实例,并使用`insert()` 方法插入数据。
```javaDBHelper dbHelper = new DBHelper(context);SQLiteDatabase db = dbHelper.getWritableDatabase();ContentValues values = new ContentValues();values.put("name", "John Doe");long newRowId = db.insert("mytable", null, values);if (newRowId != -1) {// 插入成功} else {// 插入失败}db.close();```在上述代码中,我们首先实例化了 `DBHelper` 类,并获取了可写入的数据库实例。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
每个应用程序都要使用数据,Android应用程序也不例外,Android使用开源的、与操作系统无关的SQL数据库--大名鼎鼎的SQLite。
SQLite是一款轻量级数据库,它的设计目的是嵌入式,而且它占用的资源非常少,在嵌入式设备中,可能只需要几百KB,这也是Android 系统采用SQLite 数据库的原因之一吧。
简介∙轻量级使用SQLite 只需要带一个动态库,就可以享受它的全部功能,而且那个动态库的尺寸想当小。
∙独立性SQLite 数据库的核心引擎不需要依赖第三方软件,也不需要所谓的“安装”。
∙隔离性SQLite 数据库中所有的信息(比如表、视图、触发器等)都包含在一个文件夹内,方便管理和维护。
∙跨平台SQLite 目前支持大部分操作系统,不至电脑操作系统更在众多的手机系统也是能够运行,比如:Android。
∙多语言接口SQLite 数据库支持多语言编程接口。
∙安全性SQLite 数据库通过数据库级上的独占性和共享锁来实现独立事务处理。
这意味着多个进程可以在同一时间从同一数据库读取数据,但只能有一个可以写入数据。
SQLite使用介绍首先先来看一下本篇例子继承SQLiteOpenHelper 类实现的dbHelper 类。
package com.terry;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteDatabase.CursorFactory;public class dbHelper extends SQLiteOpenHelper {private final static String DATABASE_NAME="sec_db";private final static int DATABASE_VERSION=1;private final static String TABLE_NAME="sec_pwd";public final static String FIELD_ID="_id";public final static String FIELD_TITLE="sec_Title";public dbHelper(Context context){super(context, DATABASE_NAME,null, DATABASE_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubString sql="Create table "+TABLE_NAME+"("+FIELD_ID+" integer primary key autoincrement,"+FIELD_TITLE+" text );";db.execSQL(sql);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newV ersion) {// TODO Auto-generated method stubString sql=" DROP TABLE IF EXISTS "+TABLE_NAME;db.execSQL(sql);onCreate(db);public Cursor select(){SQLiteDatabase db=this.getReadableDatabase();Cursor cursor=db.query(TABLE_NAME, null, null, null, null, nu ll, " _id desc");return cursor;}public long insert(String Title){SQLiteDatabase db=this.getWritableDatabase();ContentValues cv=new ContentValues();cv.put(FIELD_TITLE, Title);long row=db.insert(TABLE_NAME, null, cv);return row;}public void delete(int id){SQLiteDatabase db=this.getWritableDatabase();String where=FIELD_ID+"=?";String[] whereValue={Integer.toString(id)};db.delete(TABLE_NAME, where, whereValue);}public void update(int id,String Title){SQLiteDatabase db=this.getWritableDatabase();String where=FIELD_ID+"=?";String[] whereValue={Integer.toString(id)};ContentValues cv=new ContentValues();cv.put(FIELD_TITLE, Title);db.update(TABLE_NAME, cv, where, whereValue);}}创建和打开数据库上篇通过构造函数来创建数据库,看一下构造函数的方法android.database.sqlite.SQLiteOpenHelper.SQLiteOpenHelper(Cont ext context, String name, CursorFactory factory, int version)public SQLiteOpenHelper (Context context, String name, SQLiteD atabase.CursorFactory factory, int version)Since: API Level 1Create a helper object to create, open, and/or manage a databa se. The database is not actually created or opened until one of getWritableDatabase() or getReadableDatabase() is called.Parameterscontext to use to open or create the databasename of the database file, or null for an in-memory database factory to use for creating cursor objects, or null for the d efaultversion number of the database (starting at 1); if the databa se is older, onUpgrade(SQLiteDatabase, int, int) will be used to upgrade the databasePublic Methods大体可以理成如下:如果进入此函数,不存在此数据库则创建,如果存在此数据库则打开连接,只要进入此方法就可以用打开的连接获得getWritableDatabase()或getReadableDatabase()这两个方法。
∙创建表--》Create Table一个数据库中可以包含多个表,每一条数据都存在指定的表中,要创建可以通过execSQL 方法来执行一条SQL 语句。
上面的方法为代码public void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubString sql="Create table "+TABLE_NAME+"("+FIELD_ID+" i nteger primary key autoincrement,"+FIELD_TITLE+" text );";db.execSQL(sql);}上面代码创建了表名为“sec_pwd” 的数据表,表内存在一个integer 类型的主键和一个text 类型的字段,并执行创建该表。
∙添加数据--》Insert上面的代码封装了一个使用SQLite 的insert 方法,向表中添加数据,但是insert 方法要求把数据都打包到ContentValues 中,ContentValue 其实可就是一个HashTable,Key值是字段名称,Value 值是字段的值。
通过ContentValues 的put 方法就可以把数据库放到ContentValue 对象中,然后插入到表中去。
代码为:public long insert(String Title){SQLiteDatabase db=this.getWritableDatabase();ContentValues cv=new ContentValues();cv.put(FIELD_TITLE, Title);long row=db.insert(TABLE_NAME, null, cv);return row;}∙删除数据--》Delete依此类推,添加数据用Insert,那么删除数据为Deletepublic void delete(int id){SQLiteDatabase db=this.getWritableDatabase();String where=FIELD_ID+"=?";String[] whereValue={Integer.toString(id)};db.delete(TABLE_NAME, where, whereValue);}∙修改数据--》Updatepublic void update(int id,String Title){SQLiteDatabase db=this.getWritableDatabase();String where=FIELD_ID+"=?";String[] whereValue={Integer.toString(id)};ContentValues cv=new ContentValues();cv.put(FIELD_TITLE, Title);db.update(TABLE_NAME, cv, where, whereValue);}可根据自己需要修改字段自行加参数。