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

Sqlite数据库的增、删、改、查方法,第1张

概述<?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="
<?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,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,values);	}	/**	 * 插入数据 插入部分列	 */	public voID insertStuSomeColumn() {		ContentValues values = new ContentValues();		values.put("name","ooo");		values.put("age","27");		msqlitedb.insert(DataBaseHelper.table_name_STUDENT,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,new String[] { "1" });	}	public voID updataStuByIDAndOtherColumn() {		ContentValues values = new ContentValues();		values.put("name","zzz");		// 更新资源database.update(table,whereArgs)		int update = msqlitedb.update(DataBaseHelper.table_name_STUDENT,"ID=? and age=?",new String[] { "2","27" });		Log.e("TAG","" + update);	}	/**	 * 获取记录总数	 * 	 * @return	 */	public int queryStuCount() {		Cursor cursor = msqlitedb.query(DataBaseHelper.table_name_STUDENT,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,"27" },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);			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,values);					}				} else {					msqlitedb.insert(DataBaseHelper.table_name_STUDENT,values);				}			}		} catch (Exception e) {			e.printstacktrace();			throw new sqlException(e.getMessage());		} finally {			if (values != null) {				values.clear();				values = null;			}		}	}}
总结

以上是内存溢出为你收集整理的Sqlite数据库的增、删、改、查方法全部内容,希望文章能够帮你解决Sqlite数据库的增、删、改、查方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/1168488.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存