在Android的开发,重要的就是的数据库,几乎每个App中都会用到Sqlit数据库存储一些数据,
新建java类(DBConnect.java)
package com.example.sqlitedemo1;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBConnect extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "niit";//要创建的数据库名
public static final String TABLE_NAME = "emp"; //要创建的表名
public static final int DATABASE_VERSION = 1; //使用的数据库版本
//表中列名
public static final String EID = "_id"; //第一列 主键
public static final String ENAME = "EmpName"; //第二列 员工姓名
public static final String EAGE = "EmpAge"; //第三列 员工年龄
//建表 -->注意此处引号后补上空格
private static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME
+ " ( " + EID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ENAME
+ " VARCHAR( 255) , " + EAGE + " INTEGER ) ; ";
//删表
private static final String DROP_TABLE = " DROP TABLE IF EXISTS "+ TABLE_NAME;
private Context context;
//连接数据库(打开或新建)
public DBConnect(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
//建表
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);//创建表
} catch (Exception e) {
Log.e("-----ERROR-----", e.getMessage());
}
}
//若数据库需要更新 则删除旧表 创建新表 实际工作中需做好数据备份
/* (non-Javadoc)
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(
* android.database.sqlite.SQLiteDatabase,
* int 旧数据库版本号,
* int 新数据库版本号)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Log.i("-----UPDATE------", "数据库已更新");
db.execSQL(DROP_TABLE);//删除旧表
onCreate(db);//建新表
} catch (Exception e) {
Log.e("----UPDATE ERROR---", e.getMessage());
}
}
}
在此类中实现对数据库的增删改查操作,使用时就直接调用此类中的方法
public class DBQuery {
public static ArrayList dblist;//空单列集合 用于存储数据
DBConnect dConnect;//引用继承SQLiteOpenHelper类的数据库连接类
//1.生成数据库连接
public DBQuery(Context context) {
dConnect = new DBConnect(context);
}
}
1.主活动添加数据
public boolean dataInsert(String ename, int eage) {
//打开数据库交由SQLiteDatabase对象管理
SQLiteDatabase sdb = dConnect.getWritableDatabase();
//单行数据存储对象cv
ContentValues contentValues = new ContentValues();
//向行中存储数据
contentValues.put(DBConnect.ENAME, ename);
contentValues.put(DBConnect.EAGE, eage);
//将此行数据加入到表中
long id = sdb.insert(DBConnect.TABLE_NAME, null, contentValues);
//判断是否添加成功
if (id > 0)
return true;
else {
return false;
}
}
public ArrayList getAllData() {
dblist = new ArrayList();//局部容器
SQLiteDatabase sdc = dConnect.getWritableDatabase();//打开数据库
//所有列名
String[] columns = { DBConnect.EID, DBConnect.ENAME, DBConnect.EAGE };
//查询表中所有数据
Cursor cursor = sdc.query(DBConnect.TABLE_NAME, columns, null, null,null, null, null);
//逐行遍历结果集
while (cursor.moveToNext()) {
//读取当前行id
int eid = cursor.getInt(cursor.getColumnIndex(DBConnect.EID));
//读取当前行name
String empName = cursor.getString(cursor.getColumnIndex(DBConnect.ENAME));
//读取当前行age
int empAge = cursor.getInt(cursor.getColumnIndex(DBConnect.EAGE));
//将三列数据拼接装入list,作为list中一条数据
dblist.add(eid + " " + empName + " " + empAge);
}
return dblist;//将所有数据返还给要展示的组件
}
3.更新数据
/** update:参数一:要更新的数据所在表名,
* 参数二 新的数据
* 参数三:要更新数据的查找条件
* 参数四:条件的参数 数组
*
*/
public boolean updaData(int id,String name,int age){
SQLiteDatabase sdc = dConnect.getWritableDatabase();//打开数据库
String[] whereArgs={" "};
whereArgs[0]=String.valueOf(id);
ContentValues cv=new ContentValues(); //ContentValues存储基本类型的数据
cv.put(DBConnect.ENAME,name);
cv.put(DBConnect.EAGE, age);
int result=sdc.update(DBConnect.TABLE_NAME,cv,"_id=?", whereArgs);
if(result>0){
return true;
}
else{
return false;
}
}
/** query:参数一:要更新的数据所在表名,
* 参数二 要查找的列名 若设为null,则查所有
* 参数三:要更新数据的查找条件
* 参数四:条件的参数 数组
*
*/
public String querData(int id){
SQLiteDatabase sdc = dConnect.getWritableDatabase();//打开数据库
String[] whereArgs={" "};
whereArgs[0]=String.valueOf(id);
String[] columns = { DBConnect.ENAME, DBConnect.EAGE };
Cursor cursor = sdc.query(DBConnect.TABLE_NAME, columns, "_id=?", whereArgs,null,null,null,null);
String msg=null;
while(cursor.moveToNext()){
String empName = cursor.getString(cursor.getColumnIndex(DBConnect.ENAME));
//读取当前行age
int empAge = cursor.getInt(cursor.getColumnIndex(DBConnect.EAGE));
msg="EName: "+empName+" Eage : "+empAge;
}
return msg;
}
}
5.删除数据 功能;
/** delete:参数一:要更新的数据所在表名,
* 参数三:要更新数据的查找条件
* 参数四:条件的参数 数组
*/
public boolean deletData(int id){
SQLiteDatabase sdb = dConnect.getWritableDatabase();//打开数据库
String[] whereArgs={" "};
whereArgs[0]=String.valueOf(id);
Log.v("=================", "id");
int result=sdb.delete(DBConnect.TABLE_NAME,"_id=?", whereArgs);
if(result>0){
return true;
}
else{
return false;
}
}
此过程中使用了匿名内部类事件监听器
1.绑定视图
package com.example.sqlitedemo1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText name, age,id;
Button save, show,del,upd,select;//保存数据 展示数据
DBQuery mdq; //数据库操作对象
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//绑定视图
name = (EditText)findViewById(R.id.editText1);
age = (EditText) findViewById(R.id.editText2);
id = (EditText) findViewById(R.id.editText3);
result = (TextView) findViewById(R.id.textView1);
save = (Button) findViewById(R.id.button1);
show = (Button)findViewById(R.id.button2);
del = (Button)findViewById(R.id.button3);
upd= (Button)findViewById(R.id.button4);
select = (Button)findViewById(R.id.button5);
mdq = new DBQuery(this);
}
2.保存数据
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String uname = name.getText().toString(); //获取用户名
String uage = age.getText().toString(); //获取年龄
//判空操作
if( uname.isEmpty()){
name.setError("Enter Uername");
}
else if(uage.isEmpty()){
age.setError("Enter password");
}else{
//非空则添加数据
int fage = Integer.parseInt(uage);//文本转数字
boolean status = mdq.dataInsert(uname, fage); //添加数据
//是否添加成功 然后输入栏置空
if(status){
Toast.makeText(getApplicationContext(),
"Data Inserted Successfully", Toast.LENGTH_LONG).show();
name.setText("");
age.setText("");
}else{
Toast.makeText(getApplicationContext(),
"Data Inserted error", Toast.LENGTH_LONG).show();
name.setText("");
age.setText("");
}
}
}
});
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, ShowDataActivity.class);
startActivity(i);
}
});
}
}
此工程中将查到的所有数据activity_show_data.xml页面中显示出来,所有需要建一个ShowDataActivity.java类,用来传输数据
package com.example.sqlitedemo1;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ShowDataActivity extends Activity {
ListView listView;//文本展开列表,可选取
DBQuery dbq;
ArrayAdapter adapter;
//初始化活动,加载数据到ListView进行展示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_data);
listView = (ListView) findViewById(R.id.listView1);
dbq = new DBQuery(this);//打开数据库进行操作
loadData();//加载数据
}
public void loadData() {
ArrayList data = dbq.getAllData();//调用DBQuery中的查询所有数据方法,取得数据
//将数据装入适配器 data即数据
adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, data);
//将适配器装入ListView对象
listView.setAdapter(adapter);
//数据已更改
adapter.notifyDataSetChanged();
}
}
4 更新数据
upd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String uname=name.getText().toString();
int uage=Integer.parseInt(age.getText().toString());
int uid=Integer.parseInt(id.getText().toString());
boolean result=mdq.updaData(uid, uname, uage);
if(result){
Toast.makeText(getApplicationContext(),
"Data has updated", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),
"nuknown Data", Toast.LENGTH_LONG).show();
}
}
});
5 查一条数据
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
int uid=Integer.parseInt(id.getText().toString());
String re= mdq.querData(uid);
if(re!=null){
result.setText(re);
}else{
Toast.makeText(getApplicationContext(),
"nuknown Data", Toast.LENGTH_LONG).show();
}
}
});
6 删除数据
del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
int eid=Integer.parseInt(id.getText().toString());
boolean result=mdq.deletData(eid);
if(result){
Toast.makeText(getApplicationContext(),
"Data has delete", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),
"nuknown Data", Toast.LENGTH_LONG).show();
}
}
});