Android 根据sql文件创建数据库并插入数据

因为在开发客户端的时候,服务器端的有写数据是重复的,不需要再去访问服务器的,然后服务器端提供的是一个sql文件,里面包含了数据库和数据,我们这些开发客户端的不可能一行一行的进行手动入库吧?所以我就想到了直接读取sql文件进行创建数据并插入数据好了。

创建DBHelp并继承SQLiteOpenHelper

public class DBHelper extends SQLiteOpenHelper {

	private Context mContext;

	public DBHelper(Context context, String databaseName,
			CursorFactory factory, int version) {
		super(context, databaseName, factory, version);
		mContext = context;
	}

	/**
	 * 数据库第一次创建时调用
	 * */
	@Override
	public void onCreate(SQLiteDatabase db) {
		if (!tabIsExist("test", db)) {
			executeAssetsSQL(db, "test.sql");
			// db.execSQL(sql);
			//System.out.println("创建表");
		}
	}

	/**
	 * 数据库升级时调用
	 * */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// 数据库不升级
		if (newVersion <= oldVersion) {
			return;
		}
		Configuration.oldVersion = oldVersion;

		int changeCnt = newVersion - oldVersion;
		for (int i = 0; i < changeCnt; i++) {
			// 依次执行updatei_i+1文件 由1更新到2 [1-2],2更新到3 [2-3]
			String schemaName = "update" + (oldVersion + i) + "_"
					+ (oldVersion + i + 1) + ".sql";
			executeAssetsSQL(db, schemaName);
		}
	}

	/**
	 * 读取数据库文件(.sql),并执行sql语句
	 * */
	private void executeAssetsSQL(SQLiteDatabase db, String schemaName) {
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(mContext.getAssets()
					.open(Configuration.DB_PATH + "/" + schemaName)));

			//System.out.println("路径:" + Configuration.DB_PATH + "/" + schemaName);
			String line;
			String buffer = "";
			while ((line = in.readLine()) != null) {
				buffer += line;
				if (line.trim().endsWith(";")) {
					db.execSQL(buffer.replace(";", ""));
					buffer = "";
				}
			}
		} catch (IOException e) {
			Log.e("db-error", e.toString());
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				Log.e("db-error", e.toString());
			}
		}
	}

	public List<Area> selectAllCities(SQLiteDatabase db) {
		List<Area> areas = new ArrayList<Area>();
		Area area;
		String sql = "select * from test where area_level=?";
		Cursor cursor = db.rawQuery(sql, new String[] { "" + 0 });

		while(cursor.moveToNext()){
			area = new Area();
			area.setId(cursor.getInt(0));
			area.setArea_name(cursor.getString(2));
			areas.add(area);
			area = null;
		}
		cursor.close();

		return areas;
	}

	public List<Area> selectAllAreas(SQLiteDatabase db,int parent_id) {
		List<Area> areas = new ArrayList<Area>();
		Area area;
		String sql = "select * from test where parent_id=?";
		Cursor cursor = db.rawQuery(sql, new String[] { "" + parent_id });

		while(cursor.moveToNext()){
			area = new Area();
			area.setId(cursor.getInt(0));
			area.setArea_name(cursor.getString(2));
			areas.add(area);
			area = null;
		}
		cursor.close();

		return areas;
	}

	/**
	 * 判断是否存在某一张表
	 * @param tabName
	 * @param db
	 * @return
	 */
	public boolean tabIsExist(String tabName, SQLiteDatabase db) {
		boolean result = false;
		if (tabName == null) {
			return false;
		}
		Cursor cursor = null;
		try {
			String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tabName.trim() + "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}

		} catch (Exception e) {
		}
		return result;
	}

}

Configuration.java是一些常量

public class Configuration {
	public static final String DB_PATH = "schema";
	public static final String DB_NAME = "test.db";
	public static final int DB_VERSION = 1;
	public static int oldVersion = -1;

}

sql文件是放在assets->schema->test.sql

其实这个过程非常的简单易懂,就是根据路径去读取文件,然后读取文件里面的内容,再根据关键字,sqllite会自动进行相应的操作,所以这个sql文件中的sql语句一定要规范,不然会写入不了的。

在activity中调用:

dbHelper = new DBHelper(this, "test", null, 1);

dbHelper.onCreate(dbHelper.getWritableDatabase());
时间: 2024-07-28 15:41:37

Android 根据sql文件创建数据库并插入数据的相关文章

用java向mysql数据库中插入数据为空

利用java面向对像编程,向数据库中插入数据时.遇到插入的数据为空的情况.在此做一小结: 1.数据库连接正正常 2.sql语句没有问题 3.程序没有报异常 4.代码: import java.util.Scanner; import org.junit.Test;public class JDBCTest { //2).在测试方法testAAddStudent()中 //1.获取从控制台输入的Student对象:Student student=getStudentFromConsole(); /

C#同步SQL Server数据库中的数据--数据库同步工具[同步新数据]

C#同步SQL Server数据库中的数据 1. 先写个sql处理类: using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; namespace PinkDatabaseSync { class DBUtility : IDisposable { private string Server; private string

解决getJdbcTemplate往oracle数据库中插入数据返回主键出错问题

我们使用Spring中的JdbcDaoSupport往Mysql中插入数据并返回主键代码,我们使用的mysql数据库,主键在数据库中设置为自增长:该类继承自JdbcDaoSupport,所以能直接使用getJdbcTemplate() public int saveUser(String userName,int age,String password){ getJdbcTemplate().update(new PreparedStatementCreator() { public Prepa

向Oracle数据库中插入数据出错:ORA-01036 无效的变量名或数据

向Oracle数据库中插入数据出错: 经过排查,因为Update数据时没有出错,所以OracleHelper没有问题: 看异常信息提示:无效的变量和数据,应该是SQL语句的问题,调试时所传的实例UserInfo数据是正确的,所以只能是SQL语句的问题: 曾今一度怀疑这样使用Sequence是错误的,中途变换了触发器,弄了变天触发器也些错误了, 再次回到直接用序列,仔细之下,终于发现这个分号‘:’,这里应该为‘:’,实在是太小了,很难发现,以后这里最好留一个空格.

MySQL创建数据库并插入数据命令

简介: 学习mysql环境为ubantu,下面记录一些基本的创建数据库和插入数据的口令 学习资源来自实验楼:https://www.shiyanlou.com/courses/9 打开MySQL 服务并使用 root 登录: # 打开 MySQL 服务 sudo service mysql start #使用 root 用户登录,密码为空 mysql -u root 以下为实例操作:创建一个名为library的数据库,包含 book.reader 两张表,根据自己的理解安排表的内容并插入数据 新

以使用QSqlQuery向数据库中插入数据为例,做一个小结

背景: 最近在使用Qt+SQLite写一个本地数据库管理程序(使用者不懂SQL),在写向数据库中插入数据的 相关的函数时,我遇到了几个问题(暂时就这些): 1.向指定字段插入指定数据时,读取到的数据都是字符串类型,然而不同字段的数据类型是不同的,这 里需要获取不同字段的数据类型,再做类型转换 2.使用QSqlQuery插入数据时,具体实现的考虑 3.在实现一个功能时,是先将功能做出来,然后对一些最初未考虑到的问题慢慢补足,还是先尽可能考 虑到所有情况,再实现相关功能 4.此时某个函数的实现,是否

用sql删除数据库重复的数据的方法

/***********************************************两个意义上的重复记录:1.是完全重复的记录,也即所有字段均重复的记录,2.是部分关键字段重复的记录,比如username字段重复,  而其他字段不一定重复或都重复可以忽略,这类重复  问题通常要求保留重复记录中的第一条记录************************************************/ /*1.数据完全重复(用到了一个临时表#Tmp)*/CREATE TABLE ad

MyBatis直接执行SQL查询及批量插入数据

MyBatis直接执行SQL查询及批量插入数据 一.直接执行SQL查询: 1.mappers文件节选 <resultMap id="AcModelResultMap" type="com.izumi.InstanceModel">  <result column="instanceid" property="instanceID" jdbcType="VARCHAR" />  <

使用变量向SQL Server 2008中插入数据

QT通过ODBC连接数据库SQL Server 2008,进行数据插入时遇到的问题: 先把数据存入变量中,如何使用变量进行插入?插入语句该怎么写? QSqlQuery query(db); query.exec("insert into device values('"+datetime+"','"+splantNum+"','"+sdeviceNum+"','"+stemper+"','"+spress+