您的位置:首页 > 数据库

Sqlite数据库的增、删、改、查方法

2016-01-10 13:06 176 查看
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.databasedemo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:name="com.example.databasedemo.MvpApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


<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"
tools:context="com.example.databasedemo.MainActivity" >

<Button
android:id="@+id/copy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="copy" />

<Button
android:id="@+id/insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="insert" />

<Button
android:id="@+id/dele"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dele" />

<Button
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update" />

<Button
android:id="@+id/query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="query" />

</LinearLayout>


MvpApplication

package com.example.databasedemo;

import android.app.Application;

public class MvpApplication extends Application{

private static MvpApplication mApplication;

@Override
public void onCreate() {
super.onCreate();
MvpApplication.mApplication = this;
VChatSipInfoStorage.getInstance();
}

public static Application getApplication(){
return mApplication;
}
}


DataBaseHelper

package com.example.databasedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {
/**
* 数据库名字
*/
private static final String DATABASE_NAME = "dandy.db";

/**
* 学生信息表名
*/
public static final String TABLE_NAME_STUDENT = "students";
private static int version = 1;

// 构造器
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}

// 带版本更新的构造器
public DataBaseHelper(Context context, int version) {
super(context, DATABASE_NAME, null, version);
DataBaseHelper.version = version;
}

@Override
public void onCreate(SQLiteDatabase db) {
createTables(db);
}

void createTables(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME_STUDENT + " ("
+ BaseColum.ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BaseColum.NAME + " TEXT, " + BaseColum.AGE
+ " TEXT,  " + BaseColum.SEX + " TEXT, "
+ BaseColum.ADD + " TEXT" + ")";
db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

/**
* 学生信息表字段名
*/
static class BaseColum {
public static final String ID = "id";
public static final String NAME = "name";
public static final String AGE = "age";
public static final String SEX = "sex";
public static final String ADD = "address";
}
}


MainActivity

package com.example.databasedemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

private Button insert;
private Button dele;
private Button update;
private Button query;
private Button copy;

String[] nameArray = {"xxx","ooo","aaa","ggg"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VChatSipInfoStorage.getInstance();

init();

}

private void init() {

insert = (Button) findViewById(R.id.insert);
dele = (Button) findViewById(R.id.dele);
update = (Button) findViewById(R.id.update);
query = (Button) findViewById(R.id.query);
copy = (Button) findViewById(R.id.copy);

insert.setOnClickListener(this);
dele.setOnClickListener(this);
update.setOnClickListener(this);
query.setOnClickListener(this);
copy.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.copy:
copyToSDCard();
Toast.makeText(this, "已复制", 0).show();
break;
case R.id.insert:

VChatSipInfoStorage.getInstance().insertSduFromNamesArr(nameArray);
//			VChatSipInfoStorage.getInstance().insertStuAllColumn();
//			VChatSipInfoStorage.getInstance().insertStuSomeColumn();

break;

case R.id.dele:
//			VChatSipInfoStorage.getInstance().deleteStuByColumn();
//			VChatSipInfoStorage.getInstance().deleteStuById();

break;
case R.id.update:

//			VChatSipInfoStorage.getInstance().updataStuById();
VChatSipInfoStorage.getInstance().updataStuByIdAndOtherColumn();
break;
case R.id.query:

int queryStuCount = VChatSipInfoStorage.getInstance().queryStuCount();
int queryStuByColumn = VChatSipInfoStorage.getInstance().queryStuByColumn();
Log.e("TAG", "query"+queryStuByColumn+queryStuCount);

break;
default:
break;
}
}

private void copyToSDCard() {
if (!Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
Log.e("wyf", "no sd");
return;
}
this.getDatabasePath("dandy");
File dbFile = new File(this.getDatabasePath("dandy") + ".db");
Log.e("TAG", ""+dbFile.getAbsolutePath());
File file = new File(Environment.getExternalStorageDirectory(),
"dandy.db");
Log.e("TAG", ""+file.getAbsolutePath());
try {
file.createNewFile();
copyFile(dbFile, file);
} catch (IOException e) {
e.printStackTrace();
}

}

@SuppressWarnings("resource")
public static void copyFile(File src, File dst) throws IOException {

FileChannel inChannel = new FileInputStream(src).getChannel();

FileChannel outChannel = new FileOutputStream(dst).getChannel();

try {

inChannel.transferTo(0, inChannel.size(), outChannel);
Log.e("TAG", "copy");

} finally {

if (inChannel != null)

inChannel.close();

if (outChannel != null)

outChannel.close();

}

}
}


VChatSipInfoStorage

package com.example.databasedemo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Application;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class VChatSipInfoStorage {

private DataBaseHelper mDataBaseHelper;
private SQLiteDatabase mSQLitedb;

private static VChatSipInfoStorage mInstance;

public static VChatSipInfoStorage getInstance() {
if (null == mInstance) {
synchronized (VChatSipInfoStorage.class) {
if (null == mInstance) {
mInstance = new VChatSipInfoStorage();
}

}
}
return mInstance;
}

private VChatSipInfoStorage() {
super();
if (mSQLitedb == null) {
openDataBase(MvpApplication.getApplication());
}
}

private void openDataBase(Context context) {
if (mDataBaseHelper == null) {
mDataBaseHelper = new DataBaseHelper(context);
}
if (mSQLitedb == null) {
mSQLitedb = mDataBaseHelper.getWritableDatabase();
}
}

/**
* 插入数据 插入所有列
*/

public void insertStuAllColumn() {
// 准备数据
ContentValues values = new ContentValues();
values.put("name", "xxx");
values.put("age", "27");
values.put("sex", "nan");
values.put("address", "1358192");
mSQLitedb.insert(DataBaseHelper.TABLE_NAME_STUDENT, null, values);
}

/**
* 插入数据 插入部分列
*/
public void insertStuSomeColumn() {
ContentValues values = new ContentValues();
values.put("name", "ooo");
values.put("age", "27");
mSQLitedb.insert(DataBaseHelper.TABLE_NAME_STUDENT, null, values);
}

/**
* 通过id删除,可以删除唯一的一条记录
*/
public void deleteStuById() {
try {
mSQLitedb.delete(DataBaseHelper.TABLE_NAME_STUDENT, "id=?",
new String[] { "1" });
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 通过非id删除,可以删除唯一、不唯一的记录
*/
public void deleteStuByColumn() {
try {
mSQLitedb.delete(DataBaseHelper.TABLE_NAME_STUDENT, "name=?",
new String[] { "xxx" });
} catch (Exception e) {
e.printStackTrace();
}
}

public void updataStuById() {
ContentValues values = new ContentValues();
values.put("name", "yyy");

// 更新资源database.update(table, values, whereClause, whereArgs)
mSQLitedb.update(DataBaseHelper.TABLE_NAME_STUDENT, values, "id=?",
new String[] { "1" });
}

public void updataStuByIdAndOtherColumn() {
ContentValues values = new ContentValues();
values.put("name", "zzz");

// 更新资源database.update(table, values, whereClause, whereArgs)

int update = mSQLitedb.update(DataBaseHelper.TABLE_NAME_STUDENT,
values, "id=? and age=?", new String[] { "2", "27" });

Log.e("TAG", "" + update);
}

/**
* 获取记录总数
*
* @return
*/
public int queryStuCount() {
Cursor cursor = mSQLitedb.query(DataBaseHelper.TABLE_NAME_STUDENT,
null, null, null, null, null, null);
while (cursor != null && cursor.getCount() > 0 && cursor.moveToNext()) {
cursor.getInt(cursor.getColumnIndexOrThrow("id"));
cursor.getInt(cursor.getColumnIndexOrThrow("name"));
cursor.getInt(cursor.getColumnIndexOrThrow("age"));
cursor.getInt(cursor.getColumnIndexOrThrow("sex"));
cursor.getInt(cursor.getColumnIndexOrThrow("address"));
}

return cursor.getCount();
}

public int queryStuByColumn() {
Cursor cursor = mSQLitedb.query(DataBaseHelper.TABLE_NAME_STUDENT,
null, "id=? and age=?", new String[] { "2", "27" }, null, null,
null);
while (cursor != null && cursor.getCount() > 0 && cursor.moveToNext()) {
cursor.getInt(cursor.getColumnIndexOrThrow("id"));
cursor.getInt(cursor.getColumnIndexOrThrow("name"));
cursor.getInt(cursor.getColumnIndexOrThrow("age"));
cursor.getInt(cursor.getColumnIndexOrThrow("sex"));
cursor.getInt(cursor.getColumnIndexOrThrow("address"));
}

return cursor.getCount();
}

/**
* 获取所有微信好友的godinId
*/
public String[] queryAllStuName() {
Cursor cursor = null;
String names[] = null;
try {
cursor = mSQLitedb.query(DataBaseHelper.TABLE_NAME_STUDENT,
new String[] { "name" }, null, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
names = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
String name = cursor.getString(cursor
.getColumnIndex("name"));
if (!TextUtils.isEmpty(name)) {
names[i] = name;
i++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return names;
}

public void insertSduFromNamesArr(String[] nameArray) {
ContentValues values = null;
String[] names = queryAllStuName();
try {
for (int i = 0; i < nameArray.length; i++) {
values = new ContentValues();
values.put("name", nameArray[i]);
boolean contains = false;
if (names != null && names.length > 0) {
ArrayList<String> list = new ArrayList<String>(
Arrays.asList(names));
contains = list.contains(nameArray[i]);
if (contains) {
// 存在更新
continue;
} else {
// 如果不存在
mSQLitedb.insert(DataBaseHelper.TABLE_NAME_STUDENT,
null, values);
}
} else {
mSQLitedb.insert(DataBaseHelper.TABLE_NAME_STUDENT, null,
values);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
} finally {
if (values != null) {
values.clear();
values = null;
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: