android 如何连接数据库

android 如何连接数据库,第1张

这种方式通常连接一个外部的数据库,第一个参数就是数据库文件,这个数据库不是当前项目中生成的,通常放在项目的Assets目录下,当然也可以在手机内,如上面参数那个目录,前提是那个文件存在且你的程序有访问权限。

另一种使用数据库的方式是,自己创建数据库并创建相应的数据库表,参考下面的代码:

public class DatabaseHelper extends SQLiteOpenHelper {

//构造,调用父类构造,数据库名字,版本号(传入更大的版本号可以让数据库升级,onUpgrade被调用)

public DatabaseHelper(Context context) {

super(context, DatabaseConstant.DATABASE_NAME, null, DatabaseConstant.DATABASE_VERSION)

}

//数据库创建时调用,里面执行表创建语句.

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(createVoucherTable())

}

//数据库升级时调用,先删除旧表,在调用onCreate创建表.

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + DatabaseConstant.TABLE_NAME)

onCreate(db)

}

//生成 创建表的SQL语句

private String createVoucherTable() {

StringBuffer sb = new StringBuffer()

sb.append(" CREATE TABLE ").append(DatabaseConstant.TABLE_NAME).append("( ").append(“ID”)

.append(" TEXT PRIMARY KEY, ")

.append(“USER_ID”).append(" INTEGER, ").append(“SMS_CONTENT”).append(" TEXT ) ")

return sb.toString()

}

} 继承SQLiteOpenHelper并实现里面的方法.

之后:

//得到数据库助手类

helper

=

new

DatabaseHelper(context)

//通过助手类,打开一个可读写的数据库连接

SQLiteDatabase

database

=

helper.getReadableDatabase()

//查询表中所有记录

database.query(DatabaseConstant.TABLE_NAME,

null,

null,

null,

null,

null,

null)

*** 作方法是用FileInputStream读取原数据库,再用 FileOutputStream把读取到的东西写入到那个目录。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 packagecom.android.ImportDatabaseimportjava.io.Fileimportjava.io.FileNotFoundExceptionimportjava.io.FileOutputStreamimportjava.io.IOExceptionimportjava.io.InputStreamimportandroid.content.Contextimportandroid.database.sqlite.SQLiteDatabaseimportandroid.os.Environmentimportandroid.util.LogpublicclassDBManager { privatefinalintBUFFER_SIZE =400000publicstaticfinalString DB_NAME ="countries.db"//保存的数据库文件名 publicstaticfinalString PACKAGE_NAME ="com.android.ImportDatabase"publicstaticfinalString DB_PATH ="/data" + Environment.getDataDirectory().getAbsolutePath() +"/" + PACKAGE_NAME//在手机里存放数据库的位置 privateSQLiteDatabase databaseprivateContext contextDBManager(Context context) { this.context = context} publicvoidopenDatabase() { this.database =this.openDatabase(DB_PATH +"/"+ DB_NAME)} privateSQLiteDatabase openDatabase(String dbfile) { try{ if(!(newFile(dbfile).exists())) { //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库 InputStream is =this.context.getResources().openRawResource( R.raw.countries)//欲导入的数据库 FileOutputStream fos =newFileOutputStream(dbfile)byte[] buffer =newbyte[BUFFER_SIZE]intcount =0while((count = is.read(buffer)) >0) { fos.write(buffer,0, count)} fos.close()is.close()} SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null)returndb}catch(FileNotFoundException e) { Log.e("Database","File not found")e.printStackTrace()}catch(IOException e) { Log.e("Database","IO exception")e.printStackTrace()} returnnull} ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 packagecom.android.ImportDatabaseimportjava.util.ArrayListimportandroid.app.Activityimportandroid.database.Cursorimportandroid.database.sqlite.SQLiteDatabaseimportandroid.os.BundlepublicclassTaxiActivityextendsActivity { privateSQLiteDatabase databaseArrayList CITY@Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState)setContentView(R.layout.main)database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH +"/"+ DBManager.DB_NAME,null)CITY = getCity()// do something with CITY database.close()} privateArrayList getCity() { Cursor cur = database.rawQuery("SELECT city.id_city, city.name FROM taxi, city WHERE city.id_city = taxi.id_city GROUP BY city.id_city",null)if(cur !=null) { intNUM_CITY = cur.getCount()ArrayList taxicity =newArrayList(NUM_CITY)if(cur.moveToFirst()) { do{ String name = cur.getString(cur.getColumnIndex("name"))intid = cur.getInt(cur.getColumnIndex("id_city"))CityClass city =newCityClass("",0)System.out.println(name)//额外添加一句,把select到的信息输出到Logcat city.city_name = namecity.city_id = idtaxicity.add(city)}while(cur.moveToNext())} returntaxicity}else{ returnnull} } } 查看输出的结果:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9598824.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存