Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android sqlite本地數據庫

Android sqlite本地數據庫

編輯:關於Android編程

做任何開發都會用的數據庫,Android也一樣,Android一般都要用的兩個數據庫本地數據庫和遠程數據庫,本地數據庫就是sqlite,遠程數據庫的話,我一般用的是mysql,這次先了解下本地數據庫sqlite,一般數據庫類型為varchar(20) 如果你輸入個大於20位的數據時,會報錯,不能插入吧,但是sqlite裡就不一樣了,他就可以,這是sqlite的特色之一吧應該是。下來就看看sqlite的 crud:

MainActivity

package com.example.sqlite;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView t;
        
        DBOpenHelter dbopenhelper=new DBOpenHelter(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


PersonService

package com.example.sqlite;

import com.example.bean.Person;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class PersonService {
	private DBOpenHelter dbOpenHelper;
	
	public PersonService(Context context){
		
		this.dbOpenHelper=new DBOpenHelter(context);
	}
	public void save(Person person){
		SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
		StringBuilder sql=new StringBuilder(128);	//這個沒用
		sql.append("insert ");						//這個沒用
		db.execSQL("insert into person(name,phone) values(?,?)",new Object[]{person.getName(),person.getPhone()});
		db.close();
	}
	public Person find(Integer id){
		Person person=new Person();
		SQLiteDatabase db=dbOpenHelper.getReadableDatabase();
		Cursor cursor=db.rawQuery("select * from testpersion wehre name=?",new String[]{id.toString()});
		while(cursor.moveToNext()){
			int personid=cursor.getInt(cursor.getColumnIndex("id"));
		}
		return person;
	}
}

DBOpenHelter

package com.example.sqlite;

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

public class DBOpenHelter extends SQLiteOpenHelper{

public DBOpenHelter(Context context) {
super(context, "itcast.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE testpersion(persionid integer primary key autoincrement,name varchar(20))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("ALTER TABLE testpersion ADD phone VARCHAR(12) NULL");
}

}




  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved