本文主要是记录一些零碎的知识点
SQLiteOpenHelper可以帮我们创建和打开数据库,这样就可以避免重复的建表带来的数据覆盖的麻烦,而且在数据库更新时也很方便
测试界面就是两个按钮,这里就不写了,有两个onClick事件,一个写数据,一个读数据
DbHelper:就一个表,只有一个id字段,一个name字段,如果有几个表,就在onCreate里多写几个ddl语句就好
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DbHelpler extends SQLiteOpenHelper { public JohnDbHelpler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context,name,factory,version); } @Override public void onCreate(SQLiteDatabase db) { String ddl="create table users (id integer primary key autoincrement,uname text)"; db.execSQL(ddl); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String ddl="create table users (id integer primary key autoincrement,uname text)"; Log.i("john","upgrade....."); } }看看MainActivity里的实现
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import java.io.File; public class MainActivity extends AppCompatActivity { private SQLiteDatabase db; private JohnDbHelpler dbHelpler; private int i=0; private File sdcardDir; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sdcardDir= Environment.getExternalStorageDirectory(); dbHelpler=new DbHelpler(this,sdcardDir.getAbsolutePath()+"/john1.db",null,2); db=dbHelpler.getWritableDatabase(); Log.i("<span style="font-family: Arial;">MainActivity </span><span style="font-family: Arial;">", sdcardDir.getAbsolutePath() + "...............................");</span> } @Override protected void onDestroy() { super.onDestroy(); db.close(); } public void writeDB(View view) { String sql="insert into users (uname) values (?)"; try { db.beginTransaction(); db.execSQL(sql, new Object[]{"Tom" + i++}); db.setTransactionSuccessful(); } catch (RuntimeException e){ } finally { db.endTransaction(); } } public void readDB(View view) { String sql="select uname,id from users where id>?"; Cursor c=db.rawQuery(sql,new String[]{"2"}); while (c.moveToNext()){ String uname=c.getString(0); int id=c.getInt(c.getColumnIndex("id")); Log.i("MainActivity","uanme:"+uname+"........"+id); } }Dbhelper里的onUpgrade只会在DbHelpler创建时,最后一个参数版本号变化时才会执行
其他的增删改查都是db可以操作的,跟普通数据库一样