GVKun编程网logo

SQLite数据库android创建表

6

在本文中,您将会了解到关于SQLite数据库android创建表的新资讯,并给出一些关于androidSQLite数据库使用实例、AndroidSQLite数据库升级方案、AndroidSQLite数

在本文中,您将会了解到关于SQLite数据库android创建表的新资讯,并给出一些关于android SQLite数据库使用实例、Android SQLite数据库升级方案、Android SQLite数据库已损坏、android SQLite数据库总结的实用技巧。

本文目录一览:

SQLite数据库android创建表

SQLite数据库android创建表

“我得到错误”没有这样的表“,并让我尽一切可能让它消失,现在它已经消失了,但我很困惑.这是我的情况

我需要在应用程序中创建2个表.我为每个表放了一个类,它看起来像下面的代码.如果我按照这个,当我从“Table2”中提取数据时,它会打击“No Such Table”,所以我需要将DATABASE_NAME更改为其他值=“DB2”;然后“Table2”将成功创建并能够提取数据.

所以我的问题是这是确保2个表成功创建的正确方法吗?或者我不应该将表分成两类?请指教

public class DB1 extends sqliteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "DB";

// Labels table name
private static final String TABLE_STORE = "Table1";

// Labels Table Columns names
public static final String KEY_1 = "col1"; 

public RC_StoreTbl(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(sqliteDatabase db) {
    // Category table create query
    String CREATE_TABLE = "CREATE TABLE " + TABLE_STORE + "("
            +KEY_1 + " INTEGER PRIMARY KEY)";
    db.execsql(CREATE_TABLE);
}
}

另一堂课

public class DB2 extends sqliteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "DB";

// Labels table name
private static final String TABLE_STORE = "Table2";

// Labels Table Columns names
public static final String KEY_1 = "col1"; 

public RC_StoreTbl(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(sqliteDatabase db) {
    // Category table create query
    String CREATE_TABLE = "CREATE TABLE " + TABLE_STORE + "("
            +KEY_1 + " INTEGER PRIMARY KEY)";
    db.execsql(CREATE_TABLE);
}
}

解决方法:

不,你应该把表放在一个数据库类中.只需确保每当您更改代码以修改表格或添加/删除表格以清除数据或卸载应用程序并再次运行时.您很可能因为添加或修改表而出现“No Such Table”错误,在这种情况下,在您清除数据或卸载应用程序之前,不会再次调用onCreate.

android SQLite数据库使用实例

android SQLite数据库使用实例

创建数据库帮助类DbHelper.java:

package com.example.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {

	public DbHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		db.execSQL("create table if not exists tb_people"+
				"(_id integer primary key autoincrement,"+
				"name varchar(20),"+
				"phone varchar(12),"+
				"mobile varchar(12),"+
				"email varchar(30))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub

	}

}

主布局文件:

ch9_sqlmain.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="所有联系人:"
        android:textSize="15px"/>
    <LinearLayout android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView android:layout_width="40px"
            android:layout_height="wrap_content"
            android:text="编号"/>
        <TextView android:layout_width="50px"
            android:layout_height="wrap_content"
            android:text="姓名"/>
        <TextView android:layout_width="80px"
            android:layout_height="wrap_content"
            android:text="电话"/>
        <TextView android:layout_width="80px"
            android:layout_height="wrap_content"
            android:text="手机"/>
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="电子信箱"/>
    </LinearLayout>
    <ListView android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/list_people"/>

</LinearLayout>

编写ListView的Item显示布局文件ch9_peoplelist.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView android:id="@+id/id"
        android:layout_width="40px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/name"
        android:layout_width="50px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/phone"
        android:layout_width="80px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/mobile"
        android:layout_width="80px"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    

</LinearLayout>

主活动类SqlMainActivity.java:

package com.example.ch9;

import com.example.baseexample.R;
import com.example.db.DbHelper;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class SqlMainActivity extends Activity {
	private ListView list_people;
	private DbHelper dbhelper;
	private SQLiteDatabase db;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch9_sqlmain);
		
		list_people = (ListView)findViewById(R.id.list_people);
		
		dbhelper = new DbHelper(this, "Db_People", null, 1);
		
		db = dbhelper.getReadableDatabase();
		Cursor c = db.query("tb_people", new String[]{"_id","name","phone","mobile","email"}, null, null, null, null, null);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.ch9_peoplelist, c, new String[]{"_id","name","phone","mobile","email"}, new int[]{R.id.id,R.id.name,R.id.phone,R.id.mobile,R.id.email});
		
		this.list_people.setAdapter(adapter);
		this.registerForContextMenu(list_people);
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(Menu.NONE,Menu.FIRST+1,1,"添加").setIcon(android.R.drawable.ic_menu_add);
		menu.add(Menu.NONE,Menu.FIRST+1,2,"退出").setIcon(android.R.drawable.ic_menu_delete);
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case Menu.FIRST+1:
			Intent intent = new Intent();
			intent.setClass(SqlMainActivity.this, AddPeopleActivity.class);
			startActivity(intent);
			break;
		case Menu.FIRST+2:finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
		menu.setHeaderIcon(R.drawable.ic_launcher);
		menu.add(0,3,0,"修改");
		menu.add(0, 4, 0, "删除");
	}
	
	public boolean onContextItemSelected(MenuItem item){
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo)item.getMenuInfo();
		switch(item.getItemId()){
		case 3:
			String name=((TextView)menuInfo.targetView.findViewById(R.id.name)).getText().toString();
			String phone=((TextView)menuInfo.targetView.findViewById(R.id.phone)).getText().toString();
			String mobile=((TextView)menuInfo.targetView.findViewById(R.id.mobile)).getText().toString();
			String email=((TextView)menuInfo.targetView.findViewById(R.id.email)).getText().toString();
			Intent intent = new Intent();
			intent.setClass(SqlMainActivity.this, AddPeopleActivity.class);
			Bundle bundle = new Bundle();
			bundle.putLong("id", menuInfo.id);
			bundle.putString("name", name);
			bundle.putString("phone", phone);
			bundle.putString("mobile", mobile);
			bundle.putString("email", email);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case 4:
			dbhelper = new DbHelper(this,"Db_People",null,1);
			db = dbhelper.getWritableDatabase();
			db.delete("tb_people", "_id=?", new String[]{menuInfo.id+""});
			break;
		}
		
		return true;
	}
	
}

布局文件ch9_addpeople.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="用户名"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_name"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="联系电话"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_phone"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="手机"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_mobile"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="电子信箱"
            android:layout_weight="2"/>
        <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edt_email"
            android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bt_save"
            android:text="保存"
            android:layout_weight="1"/>
        <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/bt_cancel"
            android:text="取消"
            android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>

创建活动AddPeopleActivity.java:

package com.example.ch9;

import com.example.baseexample.R;
import com.example.db.DbHelper;

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddPeopleActivity extends Activity {
	private EditText edt_name;
	private EditText edt_phone;
	private EditText edt_mobile;
	private EditText edt_email;
	private Button bt_save;
	String name,phone,mobile,email;
	DbHelper dbhelper;
	SQLiteDatabase db;
	Bundle bundle;
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch9_addpeople);
		
		edt_name=(EditText)findViewById(R.id.edt_name);
		edt_phone=(EditText)findViewById(R.id.edt_phone);
		edt_mobile=(EditText)findViewById(R.id.edt_mobile);
		edt_email=(EditText)findViewById(R.id.edt_email);
		bt_save = (Button)findViewById(R.id.bt_save);
		
		bundle = this.getIntent().getExtras();
		if(bundle!=null){
			edt_name.setText(bundle.getString("name"));
			edt_phone.setText(bundle.getString("phone"));
			edt_mobile.setText(bundle.getString("mobile"));
			edt_email.setText(bundle.getString("email"));
		}
		
		bt_save.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View v) {
				name = edt_name.getText().toString();
				phone = edt_phone.getText().toString();
				mobile = edt_mobile.getText().toString();
				email = edt_email.getText().toString();
				
				ContentValues value = new ContentValues();
				value.put("name", name);
				value.put("phone", phone);
				value.put("mobile", mobile);
				value.put("email", email);
				
				DbHelper dbhelper = new DbHelper(AddPeopleActivity.this,"Db_People",null,1);
				SQLiteDatabase db = dbhelper.getWritableDatabase();
				long status;
				if(bundle!=null){
					status = db.update("tb_people", value, "_id=?", new String[]{bundle.getLong("id")+""});
				}else{
					status = db.insert("tb_people", null, value);
				}
				if(status!=-1){
					Toast.makeText(AddPeopleActivity.this, "保存成功", Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(AddPeopleActivity.this, "保存失败", Toast.LENGTH_LONG).show();
				}
			}
			
		});
	}
}






Android SQLite数据库升级方案

Android SQLite数据库升级方案

例如一个数据库表

19版本是2个字段
20版本是3个字段
21版本是4个字段

 

 

package com.yzc.atclient.service.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.allcam.atclient.app.ClientApplication;

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final String DB_NAME = "allcam_db";

    private static final int VERSION = 1;

    private static volatile DatabaseHelper instance;

    public DatabaseHelper(Context context)
    {
        this(context, DB_NAME, null, VERSION);
    }

    public DatabaseHelper(Context context, String name, CursorFactory factory, int version)
    {
        super(context, name, factory, version);
    }

    public static DatabaseHelper getInstance()
    {
        if (null == instance)
        {
            synchronized (DatabaseHelper.class)
            {
                if (null == instance)
                {
                    instance = new DatabaseHelper(ClientApplication.getAppContext());
                }
            }
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        CardUserTable.createTable(db);
        TaskStatusTable.createTable(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
          //在这里组合case 判断 升级
    }
}

 

例如:


for (int j = oldVersion; j <= newVersion; j++) {

            switch (j) {

            case 2:

          //创建临时表

                db.execSQL(TEMP_SQL_CREATE_TABLE_SUBSCRIBE);

          //执行OnCreate方法,这个方法中放的是表的初始化操作工作,比如创建新表之类的

                onCreate(db);

          //删除之前的表里面的那4条默认的数据

                for (int i = 0; i < arrWhereAct.length; i++) {

                    db.execSQL(DELETE_TEMP_SUBSCRIBE + arrWhereAct[i]);

                }

               //将临时表中的数据放入表A 

         Cursor cursor = db.rawQuery(INSERT_SUBSCRIBE, null);

                if (cursor.moveToFirst()) {

                    do {

                        db.execSQL(cursor.getString(cursor

                                .getColumnIndex("insertSQL")));

                    } while (cursor.moveToNext());

                }

                cursor.close();

          //将临时表删除掉

                db.execSQL(DROP_TEMP_SUBSCRIBE);



                break;



            default:

                break;

            }

        }


 

Android SQLite数据库已损坏

Android SQLite数据库已损坏

此链接完全描述了我的问题: http://old.nabble.com/Android-database-corruption-td28044218.html#a28044218

现在大约有300人使用我的Android应用程序,每次使用此堆栈跟踪向服务器发送崩溃报告时:

android.database.sqlite.sqliteDatabaseCorruptException: database disk image is malformed
    at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2596)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
    at android.app.ActivityThread.access$2200(ActivityThread.java:126)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:4595)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.sqlite.sqliteDatabaseCorruptException: database disk image is malformed
    at android.database.sqlite.sqliteQuery.native_fill_window(Native Method)
    at android.database.sqlite.sqliteQuery.fillWindow(sqliteQuery.java:75)
    at android.database.sqlite.sqliteCursor.fillWindow(sqliteCursor.java:295)
    at android.database.sqlite.sqliteCursor.getCount(sqliteCursor.java:276)
    at android.database.AbstractCursor.movetoPosition(AbstractCursor.java:171)
    at android.database.AbstractCursor.movetoFirst(AbstractCursor.java:248)

结果是应用程序崩溃并且数据库中的所有数据都丢失了.

需要注意的一点是,每次我读取或写入数据库时​​,我都会得到一个新的sqliteDatabase,并在完成后立即将其关闭.我这样做是为了防止这种腐败错误.

我还尝试使用单个静态对象同步所有数据库读取和写入,这似乎没有帮助.

这可能只是一个sqlite错误吗?

我在这里找到了与内置电子邮件应用程序类似的错误:http://code.google.com/p/android/issues/detail?id=5610.

这是我的代码:

public class keyvalueTableAdapter extends BaseTableAdapter {

    private String tableName;
    private String keyColumnName;
    private String valueColumnName;

    public keyvalueTableAdapter(Context context,String tableName,String keyColumnName,String valueColumnName) {
        super(context);
        this.tableName = tableName;
        this.keyColumnName = keyColumnName;
        this.valueColumnName = valueColumnName;
    }

    protected String getStringValue(int key) {
        Cursor cursor = null;
        sqliteDatabase db = null;
        String value;

        try {
            db = dbOpenHelper.getReadableDatabase();
            cursor = db.query(true,tableName,new String[] { valueColumnName },keyColumnName + "=" + key,null,null);

            if ((cursor.getCount() == 0) || !cursor.movetoFirst()) {
                value = null;
            } else {
                value = cursor.getString(0);
            }
        } finally {
            if (cursor != null) cursor.close();
            if (db != null) db.close();
            dbOpenHelper.close();
        }

        return value;
    }
}


public abstract class BaseTableAdapter {

    protected DbOpenHelper dbOpenHelper;

    public BaseTableAdapter(Context context) {
        this.dbOpenHelper = new DbOpenHelper(context,DatabaseSettings.DATABASE_NAME,DatabaseSettings.DATABASE_VERSION);
    }

}

解决方法

“the DB holds session information so
it’s not very feasible to do a backup.
The data changes by the minute”

您应该尝试使用SharedPreferences:它存储键值对(在后台,它使用文件).
存储值:

SharedPreferences sp=MyActivity.getSharedPreferences("Name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key",value);
editor.putBoolean("another",true);
editor.commit();

检索数据:

sp.getString("key","Not found"); 
// "Not found" is the default value
// if sp does not contain the specified key
sp.getBoolean("another",false); 
// false is the default value
// if sp does not contain the specified key

有关更详细的说明,请参见getSharedPreferences和SharedPreferences.

android SQLite数据库总结

android SQLite数据库总结

sqlite

sqlite是一种超轻量级的嵌入式数据库,大小只有几百KB,但是其语法支持标准sql语法,同时还遵循了数据库的ACID事务,所以学过其他数据库的开发人员都很容易掌握其使用。

sql语法就不介绍了,直接看在android中的使用

sqliteOpenHelper――封装好的数据库操作辅助类,需重写

重写方法

onCreate:初始化数据库,创建表,添加初始数据

onUpgrade:数据库版本升级时的数据库操作,如备份删除数据库等

常用方法

getReadableDatabase()    获取sqliteDatabase对象,操作数据库

getWritableDatabase()        获取sqliteDatabase对象,操作数据库

区别:在磁盘空间满或不可写时,1方法将获得只读的数据库对象,而2方法会报错,在正常情况下,获取到的都是可读写的数据库对象。

import android.content.Context;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
public class DBHelper extends sqliteOpenHelper {
 private static final String name="my";//数据库名
 private static final int version=1;//版本号
 //重写构造方法的时候选择参数少的一项
 public DBHelper(Context context) {
  //1:上下文 2:数据库名称 3:游标创建工厂 4:数据库版本 版本只能是整数 1 2 3..
  super(context,name,null,version);
 }
 //数据库的初始化 sqliteDatabase数据库操作对象
 //一般只在第一次运行和版本更新的时候调用
 @Override
 public void onCreate(sqliteDatabase db) {
  //创建数据库 主键默认自增
  db.execsql("create table student(" +
    "_id integer not null primary key autoincrement," +
    "name varchar(20)," +
    "phone varchar(11)," +
    "gender varchar(2))");
  //添加一条测试数据
  db.execsql("insert into student values(null,?,?)",new Object[]{"小黑","12345678901","男"});
 }
 /**
  * 在版本升级的时候调用
  * 修改version 为2 表示版本升级 就会调用这个方法
  * @param db 数据库操作对象
  * @param oldVersion 旧版本号
  * @param newVersion 新版本号
  */
 @Override
 public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
 }
}

在android数据库的创建是需要创建对象才能创建的

在activity类中创建出一个数据库类对象

创建好数据对象就可以操作数据了 通过sqliteDatabase获取   两种获取方法的区别上面已经提到过了

     //创建数据
  DBHelper helper =new DBHelper(this);
  //调用数据操作对象
  sqliteDatabase dbWrite=helper.getWritableDatabase();
  sqliteDatabase dbRead=helper.getReadableDatabase();

sqliteDatabase给我们提供了很多操作数据的方法 

删除:(int) delete(String table,String whereClause,String[] whereArgs) 

   table: 表名

   whereClause:where条件  列名 占位符  id=?

   whereArgs:参数值数组

添加:(long) insert(String table,String nullColumnHack,ContentValues values)  

    nullColumnHack:为空列

    ContentValues values:通过键值对存储添加的数据  key为列 value为值

    insert方法 底层是通过拼接字符串的方式 如果ContentValues是空的 拼接成的sql语句无法执行会报错 所以给一个可以为空的列当ContentValues为空时也可以执行 有兴趣的可以看一下源码

更新:(int) update(String table,ContentValues values,String[] whereArgs)

   参数意思同上

查询:(Cursor) query(boolean distinct,String table,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit)

    返回值是一个游标   这个query参数较多 简单的查询就还是写一条sql语句简单点

      boolean distinct 去重复

      String table 表名

      String[] columns要查询的列

      String selection查询条件

      String[] selectionArgs查询参数值

      String groupBy分组

      String having分组条件

      String orderBy排序

      String limit分页查询限制

关闭数据库:(void) close()

执行一条sql语句:(void) execsql(String sql) 增删改查

查询查询sql:(Cursor) rawQuery(String sql,String[] selectionArgs)

事务

try {
   db.beginTransaction();//开启事务
   // db.update();
   // db.insert();
   db.setTransactionSuccessful(); //没有设置事物成功 finally就会回滚
  } catch (Exception e) {
   e.printstacktrace();
  }finally {
   db.endTransaction();
  }

贴代码咯  执行sql语句 和封装好的方法

查询

private void query() {
  StringBuffer sb=new StringBuffer("select * from student where 1=1");
  //参数集合
  List<String> params=new ArrayList<>();
  if(!TextUtils.isEmpty(id)){
   sb.append(" and _id=?");
   params.add(id);
  }
  if(!TextUtils.isEmpty(phone)){
   sb.append(" and phone=?");
   params.add(phone);
  }
  if(!TextUtils.isEmpty(name)){
   sb.append(" and name=?");
   params.add(name);
  }
  if(!TextUtils.isEmpty(gender)){
   sb.append(" and gender=?");
   params.add(gender);
  }
  sqliteDatabase db=helper.getReadableDatabase();
  String [] projection=new String [params.size()];
  params.toArray(projection);
  //返回值 游标
  Cursor cursor=db.rawQuery(sb.toString(),projection);
    //判断游标是否为空,是否有一个值
  while(cursor!=null&&cursor.movetoNext()){
   // getColumnIndex获取列的下标 cursor.getXXXX()获取指定列的值
   String name=cursor.getString(cursor.getColumnIndex("name"));
   Integer id=cursor.getInt(cursor.getColumnIndex("_id"));
  }
 }

用不到的参数就让它为空吧   遍历数据就while循环就好咯

Cursor c = db.query("student",null);//查询并获得游标

更新

private void update() {
  StringBuffer sb=new StringBuffer("update student set ");
  List params=new ArrayList();
  if(!TextUtils.isEmpty(phone)){
   sb.append("phone=?,");
   params.add(phone);
  }
  if(!TextUtils.isEmpty(name)){
   sb.append("name=?,");
   params.add(name);
  }
  if(!TextUtils.isEmpty(gender)){
   sb.append("gender=?,");
   params.add(gender);
  }
  if (params.size()!=0){
   //更新操作拼接字符串末尾有一个","需要去除
   //删除最后一位的“,”
   sb.setLength(sb.length()-1);
   sb.append(" where 1=1");
   //通过id指定 更新那行数据
   if(!TextUtils.isEmpty(id)){
    sb.append(" and _id=?");
    params.add(id);
   }else{
    Toast.makeText(this,"请填写id",Toast.LENGTH_SHORT).show();
    return;
   }
   sqliteDatabase db=helper.getWritableDatabase();
   Object [] o=new Object[params.size()];
   params.toArray(o);//将数据存放到指定的数组中
   db.execsql(sb.toString(),o);
  }
 }
ContentValues cv = new ContentValues();//实例化ContentValues
cv.put("name","123");//添加要更改的字段及内容
String whereClause = "phone=?";//修改条件
String[] whereArgs = {"12312313213"};//修改条件的参数
db.update("student",cv,whereClause,whereArgs);//执行修改

删除

private void delete() {
  getAllText();
  //拼接sql语句
  StringBuffer sb=new StringBuffer("delete from student where 1=1");
  //保存参数的list
  List params=new ArrayList();
  //判断条件 动态拼接
  if(!TextUtils.isEmpty(id)){
   sb.append(" and _id=?");
   params.add(id);
  }
  if(!TextUtils.isEmpty(phone)){
   sb.append(" and phone=?");
   params.add(phone);
  }
  if(!TextUtils.isEmpty(name)){
   sb.append(" and name=?");
   params.add(name);
  }
  if(!TextUtils.isEmpty(gender)){
   sb.append(" and gender=?");
   params.add(gender);
  }
  sqliteDatabase db=helper.getWritableDatabase();
  if (params.size()!=0){
   Object [] o=new Object[params.size()];
   params.toArray(o);//将数据存放到指定的数组中
   //执行删除
   db.execsql(sb.toString(),o);
  }else{
   db.execsql(sb.toString());
  }
  Toast.makeText(this,"删除完成",Toast.LENGTH_SHORT).show();
 }
String whereClause = "name=?";//删除的条件
String[] whereArgs = {"123"};//删除的条件参数
db.delete("student",whereArgs);//执行删除

增加

private void insert() {//保存数据到object数组
  Object [] o=new Object[]{name,phone,gender};
  //获取数据库操作对象
  sqliteDatabase db=helper.getWritableDatabase();
  //sql:sql语句 bingArgs:参数数组
  db.execsql("insert into student values(null,o);
  //关闭连接
  db.close();
  Toast.makeText(this,"增加成功",Toast.LENGTH_SHORT).show();
 }
ContentValues cv = new ContentValues();//实例化一个ContentValues用来装载待插入的数据
cv.put("name","123"); 
db.insert("student",cv);//执行插入操作

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程小技巧!

关于SQLite数据库android创建表的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于android SQLite数据库使用实例、Android SQLite数据库升级方案、Android SQLite数据库已损坏、android SQLite数据库总结的相关信息,请在本站寻找。

本文标签: