1 package com.example.sqliteopenhelper; 2 3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5 import android.database.sqlite.SQLiteDatabase.CursorFactory; 6 import android.database.sqlite.SQLiteOpenHelper; 7 import android.util.Log; 8 9 public class MydbOpenHelper extends SQLiteOpenHelper{ 10 11 public MydbOpenHelper(Context context, String name, CursorFactory factory, int version){ 12 super(context, name, factory, version); 13 } 14 15 @Override 16 public void onCreate(SQLiteDatabase db) { 17 String createtable = "create table user(id int, name varchar(20), password char(8))"; 18 db.execSQL(createtable); 19 System.out.println("MydbOpenHelper.onCreate()"); 20 21 } 22 23 @Override 24 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 25 Log.i("MydbOpenHelper","oldVersion" + oldVersion + "newVersion" + newVersion); 26 System.out.println("MydbOpenHelper.onUpgrade()"); 27 28 } 29 }
MydbOpenHelper
1 package com.example.sqliteopenhelper; 2 3 import android.app.Activity; 4 import android.content.ContentValues; 5 import android.database.Cursor; 6 import android.database.sqlite.SQLiteDatabase; 7 import android.os.Bundle; 8 import android.util.Log; 9 import android.view.Menu; 10 import android.view.MenuItem; 11 import android.view.View; 12 13 public class MainActivity extends Activity { 14 SQLiteDatabase db = null; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 21 MydbOpenHelper dbhelper = new MydbOpenHelper(this, "userinfo.db", null, 1); 22 db = dbhelper.getWritableDatabase(); 23 24 } 25 26 public void insert(View v){ 27 ContentValues c = new ContentValues(); 28 //c.put("id", 2); 29 //c.put("name", "user222"); 30 //c.put("password", "222"); 31 32 c.put("id", 1); 33 c.put("name", "user1"); 34 c.put("password", "222"); 35 36 db.insert("user", null, c); 37 } 38 public void delete(View v){ 39 db.delete("user", "id=? and name=?", new String[]{"1","user1"}); 40 } 41 public void update(View v){ 42 ContentValues c = new ContentValues(); 43 c.put("name", "user222"); 44 c.put("password", "88888888"); 45 db.update("user", c, "id=?", new String[]{"2"}); 46 } 47 public void query(View v){ 48 String[] colums = {"id", "name", "password"}; 49 Cursor c = db.query("user", colums, null, null, null, null, null); 50 51 while(c.moveToNext()){ 52 int id = c.getInt(c.getColumnIndex("id")); 53 String username = c.getString(c.getColumnIndex("name")); 54 String password = c.getString(c.getColumnIndex("password")); 55 Log.i("sqliteopenhelper", id + "," +username+"," +password); 56 } 57 } 58 }
MainActivity.java
时间: 2024-10-27 06:57:26