Android平台使用SQLite数据库存储数据
创建一个DataBaseHelper的类,这个类是继承SQLiteOpenHelper类的,这个类中包含创建数据库、打开数据库、创建表、添加数据和查询数据的方法。代码如下:
package com.example.message_board;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.R.bool;
import android.R.integer;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
private static String DB_PATH= "";
private static String DB_NAME="Message.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1);
this.myContext = context;
Log.v("DB_PATH1",DB_PATH);
DB_PATH=myContext.getDatabasePath(DB_NAME).getPath();
Log.v("DB_PATH2",DB_PATH);
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException
{
boolean dbExist = checkDataBase();
if(dbExist)
{
//do nothing - database already exist
}
else
{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try
{
copyDataBase();
}
catch (IOException e)
{
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase()
{
SQLiteDatabase checkDB = null;
try
{
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
catch(SQLiteException e)
{
//database does't exist yet.
}
if(checkDB != null)
{
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException
{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException
{
//Open the database
String myPath = DB_PATH ;
Log.v("myPath",myPath);
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
//create a table
public void createTable() throws SQLException
{
try
{
myDataBase.execSQL("CREATE TABLE MessageTable (_id INTEGER PRIMARY KEY AUTOINCREMENT,content TEXT);");
}
catch (Exception e)
{
// TODO: handle exception
}
}
//insert the data to the database
public void insertrecord(String contentString) throws SQLException
{
try
{
//String content=contentString;
String sql="insert into MessageTable(content) values('"+contentString+"');";
Log.v("aaa", sql);
myDataBase.execSQL(sql);
Log.v("aaa_a", sql);
}
catch (Exception e)
{
Log.v("aaa_e", e.toString());
}
}
//select record
public List<String> selectrecord() throws SQLException
{
List<String> list = new ArrayList<String>();
//String[] strArr = new String[list.size()];
//list.toArray(strArr);
try
{
Cursor cr = myDataBase.rawQuery("select * from MessageTable", null);
while(cr.moveToNext())
{
//Content+=cr.getString(1);
Log.v("Record",cr.getString(1));
list.add(cr.getString(1));
}
}
catch (Exception e)
{
// TODO: handle exception
Log.v("ERR", e.toString());
}
return list;
}
@Override
public synchronized void close()
{
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
Android平台使用SQLite数据库存储数据的更多相关文章
- Android下用Sqlite数据库存储数据
第一步: 写个类 ,继承 SQLiteOpenHelper public class MyDatabaseOpenHelper extends SQLiteOpenHelper { } 第二步: ...
- Android中数据存储(三)——SQLite数据库存储数据
当一个应用程序在Android中安装后,我们在使用应用的过程中会产生很多的数据,应用都有自己的数据,那么我们应该如何存储数据呢? 数据存储方式 Android 的数据存储有5种方式: 1. Share ...
- 使用嵌入式关系型SQLite数据库存储数据
除了可以使用文件或SharedPreferences存储数据,还可以选择使用SQLite数据库存储数据. 在Android平台上,集成了一个嵌入式关系型数据库—SQLite, 1.SQLite3支持 ...
- 使用Sqlite数据库存储数据
1.Sql基本命令 1.1.创建表 表是有行和列组成的,列称为字段,行称为记录. 使用CREATE命令来创建表: 1 CREATE TABLE tab_student (studentId INTEG ...
- Android Studio 查看SQLite数据库存储位置及文件
前言: 之前开发的一个记账本APP,用的是SQLite数据库,会有一些网友问如何查看数据库,这篇博文对此进行一个说明. 操作: 1.通过DDMS(Dalvik Debug Monitor Servic ...
- QT 创建本地数据库(SQLite数据库)存储数据
注意:QT自带SQLITE数据库,不需要再安装 1.创建一个包含创建.查询.修改和删除数据库的数据库类(DataBase) DataBase.h头文件 #pragma once #include &l ...
- Android学习笔记36:使用SQLite方式存储数据
在Android中一共提供了5种数据存储方式,分别为: (1)Files:通过FileInputStream和FileOutputStream对文件进行操作.具体使用方法可以参阅博文<Andro ...
- <Android基础> (六) 数据存储 Part 3 SQLite数据库存储
6.4 SQLite数据库存储 SQLite是一种轻量级的关系型数据库,运算速度快,占用资源少. 6.4.1 创建数据库 Android为了管理数据库,专门提供了SQLiteOpenHelper帮助类 ...
- Android学习之基础知识九 — 数据存储(持久化技术)之SQLite数据库存储
前面一讲介绍了数据持久化技术的前两种:文件存储.SharedPreferences存储.下面介绍第三种技术:SQLite数据库存储 一.SQLite数据库存储 SQLite数据库是一款轻量级的关系型数 ...
随机推荐
- SuperSlidev2.1 轮播图片和无缝滚动
使用方法,狠狠的点击下面链接 http://down.admin5.com/demo/code_pop/18/562/index.html 简单使用方法如下 html <div class=&q ...
- mongodb 、nosql、 redis、 memcached 是什么?
mongodb 是一个基于文档的数据库,所有数据是从磁盘上进行读写的.MongoDB善长的是对无模式JSON数据的查询.而Redis是一个基于内存的键值数据库,它由C语言实现的,与Nginx/ Nod ...
- nginx安装-源码编译
官方文档:http://nginx.org/en/docs/configure.html 参考:http://jingyan.baidu.com/article/e2284b2b45f693e2e61 ...
- 让EditText不能自动获取焦点
在activity中放置了1个或1个以上的EditText,进入该activity的时候第一个EditText会接收焦点,我希望里面所有的EditText默认是不接收焦点的,该怎么做呢? 方法: 在第 ...
- mysql中utf8_bin、utf8_general_ci、utf8_general_cs编码区别
在mysql中存在着各种utf8编码格式,如下表: 1)utf8_bin 2)utf8_general_ci 3)utf8_general_cs utf8_bin将字符串中的每一个字符用二进制数据存储 ...
- 理解 strcpy方法
char* strcpy(char* strDest, const char* strSrc) { assert((strDest!=NULL) && (strSrc !=NULL)) ...
- Codeforces Gym H. Hell on the Markets 贪心
Problem H. Hell on the MarketsTime Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hust.edu.cn/vj ...
- C#实现注销、重启和关机代码
首先要导入对命名空间 using System.Runtime.InteropServices; 的引用 [StructLayout(LayoutKind.Sequential, Pack = 1)] ...
- QuickXdev+sublime text打造quick-cocos2d-x开发环境
Sublime 插件安装方法: 一.简单的安装方法 使用Ctrl+`快捷键或者通过View->Show Console菜单打开命令行,粘贴如下代码: import urllib.request, ...
- ElasticSearch使用
安装之前,请参考https://github.com/richardwilly98/elasticsearch-river-mongodb根据你的MongoDB版本号决定需要的elasticsearc ...