1.首先,添加sdcard权限在AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在activity中有如下代码
2.Java代码
button2.setOnClickListener(new Button.OnClickListener() {
@Override
publicvoid onClick(View arg0) {
try{
String DATABASE_PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/testdb" //将要存放于的文件夹
String DATABASE_FILENAME = "testDatabase.db"//文件名
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME
File dir = new File(DATABASE_PATH)
// 如果/sdcard/testdb目录中存在,创建这个目录
if (!dir.exists())
dir.mkdir()
// 如果在/sdcard/testdb目录中不存在
// test.db文件,则从asset\db目录中复制这个文件到
// SD卡的目录(/sdcard/testdb)
if (!(new File(databaseFilename)).exists()) {
// 获得封装testDatabase.db文件的InputStream对象
AssetManager asset=getAssets()
InputStream is=asset.open("db/testDatabase.db")
FileOutputStream fos = new FileOutputStream(databaseFilename)
byte[] buffer = newbyte[8192]
int count = 0
// 开始复制testDatabase.db文件
while ((count = is.read(buffer)) >0) {
fos.write(buffer, 0, count)
}
fos.close()
is.close()
asset.close()
}
SQLiteDatabase mSQLiteDatabase=openOrCreateDatabase(databaseFilename, Activity.MODE_PRIVATE, null)//有则打开,没有创建
Cursor cur=mSQLiteDatabase.rawQuery("select * from table1", null)
if(cur!=null){
if(cur.moveToFirst()){
do{
int idColumnIndex=cur.getColumnIndex("id")
int numColumnIndex=cur.getColumnIndex("num")
int dataColumnIndex=cur.getColumnIndex("data")
int id=cur.getInt(idColumnIndex)
int num=cur.getInt(numColumnIndex)
String data=cur.getString(dataColumnIndex)
System.out.println("id:"+id+"num:"+num+"data:"+data)
}while(cur.moveToNext())
cur.close()
}
}
mSQLiteDatabase.close()//关闭数据库连接
}catch(Exception e){
e.printStackTrace()
}
//deleteDatabase("testDatabase.db")//删除数据库
}
})
QSqlDatabase db = QSqlDatabase::addDatabase(type,SESSION_NAME)如果驱动OK,QSqlDatabase::open()失败的情况下,通过QSqlDatabase::lastError()来查找错误.
// sample
QSqlDatabase db = QSqlDatabase::addDatabase(type,SESSION_NAME)
if( db.isValid() ){
}else{
}
db.setHostName(host)
db.setPort(port)
db.setDatabaseName(dbName)
db.setUserName(user)
db.setPassword(pwd)
bool bOK = db.open()
if( bOK ){
}else{
qDebug() <<db.lastError().text()
更多相关资料可参考http://www.viiboo.cn
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)