代码下载:http://download.csdn.net/detail/u011324501/9437567
1、SQLite数据库是一个轻量级的数据库,数据库可以通过数据库级上的独占性和共享锁来实现独立事务处理。这意味着多个进程可以在同一时间从同一数据库读取数据,但只能有一个可以写入数据。
2、SQLite支持大部分标准SQL语句,增删改查语句都是通用的,分页查询语句与MySQL相同。
3、创建数据库:需要定义类继承SQLiteOpenHelper,声明构造函数四个参数,重写onCreate()方法,onUpgrade()方法。
实现代码:main.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="5dip"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/name"
android:inputType="text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/age" />
<EditText
android:id="@+id/age"
android:inputType="number"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/height" />
<EditText
android:id="@+id/heigt"
android:inputType="number"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/id" />
<EditText
android:id="@+id/id"
android:inputType="number"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/adddate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/add" />
<Button
android:id="@+id/delete"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/de" />
<Button
android:id="@+id/query"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/qu" />
<Button
android:id="@+id/deleteid"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/deid" />
<Button
android:id="@+id/update"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="@string/up" />
</LinearLayout>
<TextView
android:id="@+id/text"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
主代码:MainActivity.java
package com.example.sqllite;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText starname;
private EditText starage;
private EditText starheight;
private EditText starid;
private Button add;
private Button delete;
private Button query;
private Button deleteid;
private Button update;
private TextView text;
private DBAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获得实例
dbAdapter = new DBAdapter(this);
//打开数据库
dbAdapter.open();
initUI();
}
//初始化UI
private void initUI() {
// TODO Auto-generated method stub
starname = (EditText)findViewById(R.id.name);
starage = (EditText)findViewById(R.id.age);
starheight = (EditText)findViewById(R.id.heigt);
starid = (EditText)findViewById(R.id.id);
add = (Button)findViewById(R.id.adddate);
add.setOnClickListener(new addListener());
delete = (Button)findViewById(R.id.delete);
delete.setOnClickListener(new deleteListener());
query = (Button)findViewById(R.id.query);
query.setOnClickListener(new queryListener());
deleteid = (Button)findViewById(R.id.deleteid);
deleteid.setOnClickListener(new deleteidListener());
update = (Button)findViewById(R.id.update);
update.setOnClickListener(new updateListener());
text = (TextView)findViewById(R.id.text);
}
//添加数据
public class addListener implements OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(starname.length()!=0 && starage.length()!=0 && starheight.length()!=0){
People people = new People();
people.Name = starname.getText().toString();
people.Age = Integer.parseInt(starage.getText().toString());
people.Height = Float.parseFloat(starheight.getText().toString());
long colunm = dbAdapter.insert(people);
if(colunm == -1){
Toast.makeText(getApplication(), "添加错误!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplication(), "数据库数据为空!", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getApplication(), "输入数据不能为空!", Toast.LENGTH_SHORT).show();
}
}
}
//删除数据
public class deleteListener implements OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dbAdapter.deleteAllData();
Toast.makeText(getApplication(), "数据已删除!", Toast.LENGTH_SHORT).show();
text.setText("");
}
}
//查询数据
public class queryListener implements OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
People[] peoples = dbAdapter.queryAllData();
if(peoples == null)
{
Toast.makeText(getApplication(), "数据库数据为空!", Toast.LENGTH_SHORT).show();
return;
}
String result = "";
for (int i = 0; i < peoples.length; i++)
{
result += peoples[i].toString()+"\n";
}
text.setText(result);
}
}
//根据 id 删除
public class deleteidListener implements OnClickListener{
@SuppressWarnings("static-access")
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(starid.length()!=0){
int id = Integer.parseInt(starid.getText().toString());
long result = dbAdapter.deleteOneData(id);
Log.i(dbAdapter.DB_ACTION, "delete long :"+result);
String msg = "删除ID为"+starid.getText().toString()+"的数据" + (result>0?"成功":"失败");
text.setText(msg);
}else {
Toast.makeText(getApplication(), "id不能为空!", Toast.LENGTH_SHORT).show();
}
}
}
//更新数据
public class updateListener implements OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
People people = new People();
people.Name = starname.getText().toString();
people.Age = Integer.parseInt(starage.getText().toString());
people.Height = Float.parseFloat(starheight.getText().toString());
int id = Integer.parseInt(starid.getText().toString());
long count = dbAdapter.updateOneData(id, people);
if(count == -1 )
{
Toast.makeText(getApplication(), "更新错误!!", Toast.LENGTH_SHORT).show();
text.setText("");
}
else
{
Toast.makeText(getApplication(),"更新成功"+"更新数据第"+String.valueOf(id)+"条", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
dbAdapter.close();//关闭数据库
}
}
数据库:DBAdapter.java
package com.example.sqllite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
/**
* @author
*
*/
public class DBAdapter
{
public static final String DB_ACTION="db_action";//LogCat
private static final String DB_NAME="people.db";//数据库名
private static final String DB_TABLE="peopleinfo";//数据库表名
private static final int DB_VERSION=1;//数据库版本号
public static final String KEY_ID = "_id"; //表属性ID
public static final String KEY_NAME = "name";//表属性name
public static final String KEY_AGE = "age";//表属性age
public static final String KEY_HEIGHT = "height";//表属性height
private SQLiteDatabase db ;
private Context xContext ;
private DBOpenHelper dbOpenHelper ;
public DBAdapter(Context context)
{
xContext = context ;
}
/** 空间不够存储的时候设为只读
* @throws SQLiteException
*/
public void open() throws SQLiteException
{
dbOpenHelper = new DBOpenHelper(xContext, DB_NAME, null,DB_VERSION);
try
{
db = dbOpenHelper.getWritableDatabase();
}
catch (SQLiteException e)
{
db = dbOpenHelper.getReadableDatabase();
}
}
public void close()
{
if(db != null)
{
db.close();
db = null;
}
}
/**
* 向表中添加一条数据
* @param people
* @return
*/
public long insert(People people)
{
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, people.Name);
newValues.put(KEY_AGE, people.Age);
newValues.put(KEY_HEIGHT, people.Height);
return db.insert(DB_TABLE, null, newValues);
}
/**
* 删除一条数据
* @param id
* @return
*/
public long deleteOneData(long id)
{
return db.delete(DB_TABLE, KEY_ID+"="+id, null );
}
/**
* 删除所有数据
* @return
*/
public long deleteAllData()
{
return db.delete(DB_TABLE, null, null);
}
/**
* 根据id查询数据的代码
* @param id
* @return
*/
public People[] queryOneData(long id)
{
Cursor result = db.query(DB_TABLE, new String[] {KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
KEY_ID+"="+id, null, null, null, null);
return ConvertToPeople(result) ;
}
/**
* 查询全部数据的代码
* @return
*/
public People[] queryAllData()
{
Cursor result = db.query(DB_TABLE, new String[] {KEY_ID,KEY_NAME,KEY_AGE,KEY_HEIGHT},
null, null, null, null, null);
return ConvertToPeople(result);
}
public long updateOneData(long id ,People people)
{
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, people.Name);
newValues.put(KEY_AGE, people.Age);
newValues.put(KEY_HEIGHT, people.Height);
return db.update(DB_TABLE, newValues, KEY_ID+"="+id, null);
}
private People[] ConvertToPeople(Cursor cursor)
{
int resultCounts = cursor.getCount();
if(resultCounts == 0 || !cursor.moveToFirst())
{
return null ;
}
People[] peoples = new People[resultCounts];
Log.i(DB_ACTION, "PeoPle len:"+peoples.length);
for (int i = 0; i < resultCounts; i++)
{
peoples[i] = new People();
peoples[i].ID = cursor.getInt(0);
peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));
peoples[i].Age = cursor.getInt(cursor.getColumnIndex(KEY_AGE));
peoples[i].Height = cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT));
Log.i(DB_ACTION, "people "+i+"info :"+peoples[i].toString());
cursor.moveToNext();
}
return peoples;
}
/**
* 静态Helper类,用于建立、更新和打开数据库
*/
private static class DBOpenHelper extends SQLiteOpenHelper
{
/*
* 手动建库代码
CREATE TABLE peopleinfo
(_id integer primary key autoincrement,
name text not null,
age integer,
height float);*/
private static final String DB_CREATE=
"CREATE TABLE "+DB_TABLE
+" ("+KEY_ID+" integer primary key autoincrement, "
+KEY_NAME+" text not null, "
+KEY_AGE+" integer,"+
KEY_HEIGHT+" float);";
public DBOpenHelper(Context context, String name,
CursorFactory factory, int version)
{
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE);
Log.i(DB_ACTION, "onCreate");
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)
{
//函数在数据库需要升级时被调用,
//一般用来删除旧的数据库表,
//并将数据转移到新版本的数据库表中
_db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
onCreate(_db);
Log.i(DB_ACTION, "Upgrade");
}
}
}
代码下载地址:http://download.csdn.net/detail/u011324501/9437567