创建表--主键自增长
表一:创建自增长的主键
//正确语句 create table if not exists table_people_profile (ID INTEGER primary key autoincrement, name text); //错误语句 create table if not exists table_people_profile (ID INTEGER autoincrement, name text, primary key (ID)); create table if not exists table_people_profile (ID INTEGER auto_increment, name text, primary key (ID)); create table if not exists table_people_profile (ID INTEGER primary key auto_increment, name text);
效果图
注意,系统会维持一个表记录当前表主键最后的值
如果多张表都存在自动增长主键情况
创建表--主键自增长
数据表操作:
//增加一个字段(authorID) alter table table_works_size add authorID integer //设置字段(authorID)所有值为 11 UPDATE table_works_size SET authorID = 11 //更改字段名称
导出数据库
遇到数据库出现问题,调试过程会比较麻烦,如:表是否创建成功,数据是否完整等,通过代码查询数据表较为的麻烦。如果把数据库导出到SD上,直接打开数据库,查看相关表及数据方便很多。
//获取数据库文件路径,文件拷贝到SD
String pathDB = getDatabasePath("xxx.db").getAbsolutePath(); String sdPathDB = "/mnt/sdcard/xxx.db" //要复制的目录下的所有非子目录(文件夹)文件拷贝 public static void CopySdcardFile(String fromFile, String toFile) { try { InputStream fosfrom = new FileInputStream(fromFile); OutputStream fosto = new FileOutputStream(toFile); byte bt[] = new byte[1024]; int c; while ((c = fosfrom.read(bt)) > 0) { fosto.write(bt, 0, c); } fosfrom.close(); fosto.close(); } catch (Exception ex) { } }
导出的数据库截图
预置数据库
/assets/xxx.db 拷贝到 /data/data/packageName/xxx.db
String DB_PATH = "/data/data/packageName/databases/"; String DB_NAME = "xxx.db"; //判断是否存在数据库,不存在则拷贝 if ((new File(DB_PATH + DB_NAME)).exists() == false) { String assetsPath = "xxx.db"; File f = new File(DB_PATH); if (f.exists() == false) { f.mkdir(); } FileCopy.fileCopyFromAssetsTo(assetsPath, DB_PATH + DB_NAME); }
/** * 文件拷贝 * * @param fromFilePath * @param toFilePath */ public void fileCopyFromAssetsTo(String fromFilePath, String toFilePath) { try { InputStream inputStream = getResourceAsStream("/assets/" + fromFilePath); OutputStream outputStream = new FileOutputStream(new File(toFilePath)); byte[] bytes = new byte[1024]; int line; while ((line = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, line); } outputStream.flush(); outputStream.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }