Sqlite数据库基础操作
摘要:在应用中新建一个数据库,并创建一个数据表写入数据,然后读取表中数据并展示.
主要逻辑:
1.通过继承SQLiteOpenHelper自定义类,定制数据库的表结构,初始化,升级操作
2.实例化SQLiteOpenHelper,通过getReadableDatabase()创建数据库并且获取SQLiteDatabase示例
3.SQLiteDatabase的示例后可以实现对数据库的多种操作,如查询库中的表信息
一.新建一个类继承SQLiteOpenHelper
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MyOpenHelper extends SQLiteOpenHelper { public MyOpenHelper( Context context) { //通过传入参数,可以定义数据库名,版本号.在这里直接写死 super(context,"Account.db",null,1); } //表结构的初始化 @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table info (id integer primary key autoincrement,name varchar(20),money varchar(20))"); //写死 db.execSQL("insert into info (name,money)values(‘张三‘,‘2000‘)"); db.execSQL("insert into info (name,money)values(‘李四‘,‘5000‘)"); //不写死 db.execSQL("insert into info (name,money)values(?,?)",new String[]{"小狗","666"}); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
二.创建sqlitedatabase数据库
import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SQLiteOpenHelper myOpenHelper=new MyOpenHelper(getApplicationContext()); SQLiteDatabase database=myOpenHelper.getReadableDatabase(); Cursor cursor=database.query("info",null,null,null,null,null,null); if (cursor!=null&&cursor.getCount()>0){ while (cursor.moveToNext()){ System.out.println(cursor.getString(1)); System.out.println(cursor.getString(2)); } } } }