Android生成表对应的类与访问表对应的类

之前的篇幅中也提到,在开发Android的项目中发现,手写表对应的类和访问表对应的类,都是大量重复工作,像属性、set方法、get方法、从游标Cursor获取数据存放到表对应的对象中、将表对应的对象存放到ContentValues,自己觉得在开发中觉得没必要在这些代码上浪费过多的时间,所以去网上找了找,看有没有生成上述两种类的工具,结果没找到,然后自己就花了3天多的时间自己写了个,没有什么难度,由于时间有限,写的比较简单,或多或少会有遗漏,请大侠帮忙补充。

主要实现机制就是自定义一个XML文件,该XML中有表、列等属性,通过解析生成需要东东。

为了能将自定义XML更加完善,自己又学了一下DTD,目前我写的DTD可能不是很完善,仅构建了简单的表所需要的要素。

下面把代码贴出来,和大家分享,也希望在大家的帮助下把这个东东做的更加完善。 

 

package com.jingtuo.android.common.db;

import java.util.List;
import java.util.Map;

/**
 * 数据库
 * @author JingTuo
 *
 */
public class JtSqlite {
	
	private String name;
	
	private List<Table> tables;
	
	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}
	

	public List<Table> getTables() {
		return tables;
	}


	public void setTables(List<Table> tables) {
		this.tables = tables;
	}

	/**
	 * 表
	 * @author JingTuo
	 *
	 */
	public static class Table {
		
		private List<Column> columns;
		
		private Map<String, String> attributes;

		private String primarykey;
		
		public List<Column> getColumns() {
			return columns;
		}

		public void setColumns(List<Column> columns) {
			this.columns = columns;
		}

		public Map<String, String> getAttributes() {
			return attributes;
		}

		public void setAttributes(Map<String, String> attributes) {
			this.attributes = attributes;
		}


		public String getPrimarykey() {
			return primarykey;
		}

		public void setPrimarykey(String primarykey) {
			this.primarykey = primarykey;
		}


		/**
		 * 字段
		 * @author JingTuo
		 *
		 */
		public static class Column{
		
			private String javaType;
						
			private Map<String, String> attributes;
			
			public String getJavaType() {
				return javaType;
			}

			public void setJavaType(String javaType) {
				this.javaType = javaType;
			}

			public Map<String, String> getAttributes() {
				return attributes;
			}

			public void setAttributes(Map<String, String> attributes) {
				this.attributes = attributes;
			}

		}
	}
}

 

package com.jingtuo.android.common.db;

import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlPullParser;

import com.jingtuo.android.common.db.JtSqlite.Table;
import com.jingtuo.android.common.db.JtSqlite.Table.Column;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * 本类中有生成实体类、生成表创建语句、创建数据库等方法<br>
 * 在Android中使用,可以不做改动<br>
 * 在Web应用服务器(仅适合Win32)中使用,会缺少一些类,直接注释掉即可,但是需要下载sqlitejdbc.jar和sqlitejdbc.dll。
 * 
 * @author JingTuo
 * 
 */
public class JtSqliteUtils {

	public static final String TAG_DB = "db";
	public static final String TAG_TABLE = "table";
	public static final String TAG_COLUMN = "column";
	public static final String TAG_PRIMARYKEY = "primary_key";

	public static final String ATTR_NAME = "name";
	public static final String ATTR_DATATYPE = "datatype";
	public static final String ATTR_COMMENT = "comment";
	public static final String ATTR_DEFAULT = "default";
	public static final String ATTR_CONSTRAINT = "constraint";
	public static final String ATTR_COLUMN = "column";

	private static String path;
	
	/**
	 * 设置数据库文件路径
	 * @param path
	 */
	public static void setPath(String path) {
		JtSqliteUtils.path = path;
	}

	/**
	 * 
	 * @param path
	 * @param sqls
	 */
	public static void createDB(String path, List<String> sqls) {
		SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(path, null, null);
		if (sqls != null && sqls.size() >= 1) {
			for (int i = 0; i < sqls.size(); i++) {
				db.execSQL(sqls.get(i));
			}
		}
		JtSqliteUtils.path = path;
	}

	/**
	 * 获取只读数据库
	 * 
	 * @return
	 */
	public static SQLiteDatabase getRoDb() {
		return SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
	}

	/**
	 * 获取读写数据库
	 * 
	 * @return
	 */
	public static SQLiteDatabase getRwDb() {
		return SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
	}

	/**
	 * 使用xmlpullparser获取数据库对象
	 * 
	 * @param xmlPath
	 * @return
	 */
	public static JtSqlite getDB(Context context, int xmlId) {
		JtSqlite db = new JtSqlite();
		try {
			XmlPullParser parser = context.getResources().getXml(xmlId);
			int eventType = parser.getEventType();
			String startTag = null;
			String endTag = null;
			List<Table> tables = new ArrayList<Table>();
			Table table = null;
			Column column = null;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					eventType = parser.next();
					break;
				case XmlPullParser.START_TAG:
					startTag = parser.getName();
					if (startTag.equals(TAG_DB)) {// 数据库标签
						db.setName(getValue(parser, ATTR_NAME));
					} else if (startTag.equals(TAG_TABLE)) {// 表标签
						table = new Table();
						Map<String, String> map = new HashMap<String, String>();
						for (int i = 0; i < parser.getAttributeCount(); i++) {
							map.put(parser.getAttributeName(i), parser.getAttributeValue(i));
						}
						table.setAttributes(map);
						table.setColumns(new ArrayList<Column>());
					} else if (startTag.equals(TAG_COLUMN)) {// 字段标签
						column = new Column();
						Map<String, String> map = new HashMap<String, String>();
						for (int i = 0; i < parser.getAttributeCount(); i++) {
							map.put(parser.getAttributeName(i), parser.getAttributeValue(i));
						}
						column.setAttributes(map);
						table.getColumns().add(column);
					} else if (startTag.equals(TAG_PRIMARYKEY)) {
						String name = parser.getAttributeName(0);
						if (name.equals(ATTR_COLUMN)) {
							table.setPrimarykey(parser.getAttributeValue(0));
						}
					} else {// 未知标签不作处理

					}
					eventType = parser.next();
					break;
				case XmlPullParser.END_TAG:
					endTag = parser.getName();
					if (endTag.equals(TAG_TABLE)) {
						tables.add(table);
					}
					eventType = parser.next();
					break;
				case XmlPullParser.TEXT:
					eventType = parser.next();
					break;
				default:
					break;
				}
			}
			db.setTables(tables);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return db;
	}

	/**
	 * 使用dom解析获取数据库对象
	 * 
	 * @param xmlPath
	 * @return
	 */
	public static JtSqlite getDBbyDomParser(String xmlPath) {
		JtSqlite db = new JtSqlite();
		try {
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(new File(xmlPath));
			Element root = document.getDocumentElement();
			db.setName(root.getAttribute(ATTR_NAME));
			List<Table> tables = new ArrayList<Table>();
			NodeList tableList = root.getChildNodes();
			Node tableNode = null;
			Node child = null;
			if (tableList != null && tableList.getLength() >= 1) {
				for (int i = 0; i < tableList.getLength(); i++) {
					tableNode = tableList.item(i);
					if (TAG_TABLE.equals(tableNode.getNodeName())) {
						Table table = new Table();
						// 设置属性
						table.setAttributes(getAttributes(tableNode));
						// 设置字段
						NodeList columnList = tableNode.getChildNodes();
						List<Column> columns = new ArrayList<Column>();
						if (columnList != null && columnList.getLength() >= 1) {
							for (int j = 0; j < columnList.getLength(); j++) {
								child = columnList.item(j);
								if (TAG_COLUMN.equals(child.getNodeName())) {
									Column column = new Column();
									column.setAttributes(getAttributes(child));
									column.setJavaType(toJavaType(column.getAttributes().get(ATTR_DATATYPE)));
									columns.add(column);
								} else if (TAG_PRIMARYKEY.equals(child.getNodeName())) {
									table.setPrimarykey(getAttributes(child).get(ATTR_COLUMN));
								} else {
									continue;
								}
							}
						}
						table.setColumns(columns);
						tables.add(table);
					} else {
						continue;
					}
				}
			}
			db.setTables(tables);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return db;
	}

	/**
	 * 根据xml id文件生成表创建sql
	 * 
	 * @param file
	 */
	public static List<String> createSQL(JtSqlite db) {
		List<String> list = new ArrayList<String>();
		try {
			StringBuilder stringBuilder = null;
			List<Table> tables = db.getTables();
			if (tables != null && tables.size() >= 1) {
				for (int i = 0; i < tables.size(); i++) {
					Table table = tables.get(i);
					stringBuilder = new StringBuilder();
					stringBuilder.append("CREATE TABLE IF NOT EXISTS " + table.getAttributes().get(ATTR_NAME) + "(");
					List<Column> columns = table.getColumns();
					if (columns != null && columns.size() >= 1) {
						for (int j = 0; j < columns.size(); j++) {
							Column column = columns.get(j);
							// 字段名
							String name = column.getAttributes().get(ATTR_NAME);
							if (name != null) {
								stringBuilder.append(name);
							}
							// 字段类型
							String type = column.getAttributes().get(ATTR_DATATYPE);
							if (type != null) {
								stringBuilder.append(" " + type);
							}
							// 字段约束
							String constraint = column.getAttributes().get(ATTR_CONSTRAINT);
							if (constraint != null) {
								if (constraint.equals("NOTNULL")) {
									constraint = "NOT NULL";
								}
								stringBuilder.append(" " + constraint);
							}
							String def = column.getAttributes().get(ATTR_DEFAULT);
							if (def != null) {
								stringBuilder.append(" DEFAULT(" + def + ")");
							}
							stringBuilder.append(",");
						}
					}
					String sql = null;
					if (table.getPrimarykey() != null) {
						stringBuilder.append("PRIMARY KEY(" + table.getPrimarykey() + ")");
						stringBuilder.append(")");
						sql = stringBuilder.toString();
					} else {
						sql = stringBuilder.toString();
						sql = sql.substring(0, sql.length() - 1) + ")";
					}
					list.add(sql);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 创建与数据库表对应的类 目前仅限简单类型的表,不支持自定义类型主键
	 * 
	 * @param xmlPath
	 * @param srcPath
	 * @param packageName
	 */
	public static void createClass(String xmlPath, String srcPath, String packageName) {
		try {
			String packagePath = null;
			File packageFile = null;
			if (srcPath.endsWith("\\") || srcPath.endsWith("/")) {
				srcPath = srcPath.substring(0, srcPath.length() - 1);
			}
			if (packageName != null) {
				packagePath = srcPath + "/" + packageName.replaceAll("\\.", "/");
			} else {
				packagePath = srcPath;
			}
			packageFile = new File(packagePath);
			if (!packageFile.exists()) {// 如果文件不存在
				packageFile.mkdirs();
			} else {// 如果文件存在,则删除已存在的文件
				File[] files = packageFile.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].exists()) {
						files[i].delete();
					}
				}
			}
			// 创建文件
			File tableFolder = new File(packageFile, "table");
			File accessFolder = new File(packageFile, "access");
			tableFolder.mkdir();
			accessFolder.mkdir();

			JtSqlite db = getDBbyDomParser(xmlPath);
			List<Table> tables = db.getTables();
			if (tables == null || tables.size() <= 0) {
				return;
			}

			// 生成实体类文件
			for (int i = 0; i < tables.size(); i++) {
				Table table = tables.get(i);
				Map<String, String> tableAttributes = table.getAttributes();
				String tableName = tableAttributes.get(ATTR_NAME);
				String className = firstUpperCase(tableName) + "Base";
				String comment = tableAttributes.get(ATTR_COMMENT);
				if (comment == null) {
					comment = "";
				}

				// 创建实体类--表
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.append("package " + packageName + ".table;\n\n");
				stringBuilder.append("/**\n");
				stringBuilder.append(" * primary key(" + table.getPrimarykey() + ")\n");
				stringBuilder.append(" * " + comment + "\n");
				stringBuilder.append(" * @author JingTuo\n");
				stringBuilder.append(" */\n");
				stringBuilder.append("public class " + className + " {\n\n");
				List<Column> columns = table.getColumns();
				if (columns != null && columns.size() >= 1) {
					for (int j = 0; j < columns.size(); j++) {
						Column column = table.getColumns().get(j);
						Map<String, String> columnAttributes = column.getAttributes();
						String columnName = columnAttributes.get(ATTR_NAME);
						// 注释
						comment = columnAttributes.get(ATTR_COMMENT);
						if (comment == null) {
							comment = "";
						}

						// 缺省值
						String def = columnAttributes.get(ATTR_DEFAULT);
						if (def == null) {
							if ("String".equals(column.getJavaType()) || "byte[]".equals(column.getJavaType())) {
								def = "null";
							} else if ("int".equals(column.getJavaType())) {
								def = "0";
							} else if ("float".equals(column.getJavaType())) {
								def = "0.0f";
							} else {
								def = "null";
							}
						}

						stringBuilder.append("\t/**\n");
						stringBuilder.append("\t *" + comment + "\n");
						stringBuilder.append("\t */\n");
						stringBuilder.append("\tprivate " + column.getJavaType() + " " + columnName + " = " + def + ";\n\n");
						stringBuilder.append("\tpublic void set" + firstUpperCase(columnName) + "(" + column.getJavaType() + " " + columnName
								+ "){\n");
						stringBuilder.append("\t\tthis." + columnName + " = " + columnName + ";\n");
						stringBuilder.append("\t}\n\n");
						stringBuilder.append("\tpublic " + column.getJavaType() + " get" + firstUpperCase(columnName) + "(){\n");
						stringBuilder.append("\t\treturn this." + columnName + ";\n");
						stringBuilder.append("\t}\n\n");
					}
				}

				stringBuilder.append("}");
				File tableFile = new File(tableFolder, className + ".java");
				packageFile.createNewFile();
				FileWriter fileWriter = new FileWriter(tableFile);
				fileWriter.write(stringBuilder.toString());
				fileWriter.flush();
				fileWriter.close();

				// 创建实体类--访问表
				stringBuilder = new StringBuilder();
				stringBuilder.append("package " + packageName + ".access;\n\n");
				stringBuilder.append("import com.jingtuo.android.common.db.JtSqliteUtils;\n");
				stringBuilder.append("import com.jingtuo.android.db.table." + className + ";\n");
				stringBuilder.append("import android.content.ContentValues;\n");
				stringBuilder.append("import android.database.Cursor;\n");
				stringBuilder.append("import android.database.sqlite.SQLiteDatabase;\n");
				stringBuilder.append("import java.util.ArrayList;\n");
				stringBuilder.append("import java.util.List;\n\n");

				String accessClassName = firstUpperCase(tableName) + "AccessBase";
				stringBuilder.append("\n");
				stringBuilder.append("/**\n");
				stringBuilder.append(" * \n");
				stringBuilder.append(" * @author JingTuo\n");
				stringBuilder.append(" */\n");
				stringBuilder.append("public class " + accessClassName + " {\n\n");

				String objName = firstLowerCase(tableName);
				// find方法
				stringBuilder.append("\tpublic static " + className + " find(");
				String primarykey = table.getPrimarykey();
				String[] array = primarykey.split(",");
				String temp = "";
				for (int j = 0; j < array.length; j++) {
					temp += getJavaType(array[j], table.getColumns()) + " " + array[j] + ",";
				}
				temp = temp.substring(0, temp.length() - 1);
				stringBuilder.append(temp + "){\n");
				stringBuilder.append("\t\t" + className + " " + objName + " = null;\n");
				stringBuilder.append("\t\tSQLiteDatabase db = null;\n");
				stringBuilder.append("\t\tCursor cursor = null;\n");
				stringBuilder.append("\t\ttry{\n");
				stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRoDb();\n");
				stringBuilder.append("\t\t\tcursor = db.query(\"" + tableName + "\",null,\"");

				// 查询条件
				String where = "";
				for (int j = 0; j < array.length; j++) {
					where += array[j] + "=? and ";
				}
				where = where.substring(0, where.length() - 5);
				stringBuilder.append(where + "\", new String[]{");

				// 查询值
				temp = "";
				for (int j = 0; j < array.length; j++) {
					temp += array[j] + " + \"\",";
				}
				temp = temp.substring(0, temp.length() - 1);
				stringBuilder.append(temp + "},null,null,null);\n");
				stringBuilder.append("\t\t\tif(cursor!=null&&cursor.moveToNext()){\n");
				stringBuilder.append("\t\t\t\t" + objName + " = toObject(cursor);\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}catch(Exception e){\n");
				stringBuilder.append("\t\t\te.printStackTrace();\n");
				stringBuilder.append("\t\t}finally{\n");
				stringBuilder.append("\t\t\tif(cursor!=null){\n");
				stringBuilder.append("\t\t\t\tcursor.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t\tif(db!=null){\n");
				stringBuilder.append("\t\t\t\tdb.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}\n");
				stringBuilder.append("\t\treturn " + objName + ";\n");
				stringBuilder.append("\t}\n\n");

				// 查询方法
				stringBuilder.append("\tpublic static List<" + className + "> find(String where, String[] whereValues){\n");
				stringBuilder.append("\t\t" + className + " " + objName + " = null;\n");
				stringBuilder.append("\t\tSQLiteDatabase db = null;\n");
				stringBuilder.append("\t\tCursor cursor = null;\n");
				stringBuilder.append("\t\tList<" + className + "> result = new ArrayList<" + className + ">();\n");
				stringBuilder.append("\t\ttry{\n");
				stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRoDb();\n");
				stringBuilder.append("\t\t\tcursor = db.query(\"" + tableName + "\",null,where,whereValues,null,null,null);\n");
				stringBuilder.append("\t\t\twhile(cursor!=null&&cursor.moveToNext()){\n");
				stringBuilder.append("\t\t\t\t" + objName + " = toObject(cursor);\n");
				stringBuilder.append("\t\t\t\tresult.add(" + objName + ");\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}catch(Exception e){\n");
				stringBuilder.append("\t\t\te.printStackTrace();\n");
				stringBuilder.append("\t\t}finally{\n");
				stringBuilder.append("\t\t\tif(cursor!=null){\n");
				stringBuilder.append("\t\t\t\tcursor.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t\tif(db!=null){\n");
				stringBuilder.append("\t\t\t\tdb.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}\n");
				stringBuilder.append("\t\treturn result;\n");
				stringBuilder.append("\t}\n\n");

				// insert方法
				stringBuilder.append("\tpublic static void insert(" + className + " " + objName + "){\n");
				stringBuilder.append("\t\tSQLiteDatabase db = null;\n");
				stringBuilder.append("\t\ttry{\n");
				stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRwDb();\n");
				stringBuilder.append("\t\t\tdb.beginTransaction();\n");
				stringBuilder.append("\t\t\tdb.insert(\"" + tableName + "\", null, toValues(" + objName + "));\n");
				stringBuilder.append("\t\t\tdb.setTransactionSuccessful();\n");
				stringBuilder.append("\t\t}catch(Exception e){\n");
				stringBuilder.append("\t\t\te.printStackTrace();\n");
				stringBuilder.append("\t\t}finally{\n");
				stringBuilder.append("\t\t\tif(db!=null){\n");
				stringBuilder.append("\t\t\t\tdb.endTransaction();\n");
				stringBuilder.append("\t\t\t\tdb.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}\n");
				stringBuilder.append("\t}\n\n");

				// update方法
				stringBuilder.append("\tpublic static void update(" + className + " " + objName + "){\n");
				stringBuilder.append("\t\tSQLiteDatabase db = null;\n");
				stringBuilder.append("\t\ttry{\n");
				stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRwDb();\n");
				stringBuilder.append("\t\t\tdb.beginTransaction();\n");
				String whereValues = "";
				for (int j = 0; j < array.length; j++) {
					whereValues += objName + ".get" + firstUpperCase(array[j]) + "() + \"\",";
				}
				whereValues = whereValues.substring(0, whereValues.length() - 1);
				stringBuilder.append("\t\t\tdb.update(\"" + tableName + "\", toValues(" + objName + "), \"" + where + "\", new String[]{"
						+ whereValues + "});\n");
				stringBuilder.append("\t\t\tdb.setTransactionSuccessful();\n");
				stringBuilder.append("\t\t}catch(Exception e){\n");
				stringBuilder.append("\t\t\te.printStackTrace();\n");
				stringBuilder.append("\t\t}finally{\n");
				stringBuilder.append("\t\t\tif(db!=null){\n");
				stringBuilder.append("\t\t\t\tdb.endTransaction();\n");
				stringBuilder.append("\t\t\t\tdb.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}\n");
				stringBuilder.append("\t}\n\n");

				// delelte方法
				stringBuilder.append("\tpublic static void delete(String where, String[] whereValues){\n");
				stringBuilder.append("\t\tSQLiteDatabase db = null;\n");
				stringBuilder.append("\t\ttry{\n");
				stringBuilder.append("\t\t\tdb = JtSqliteUtils.getRwDb();\n");
				stringBuilder.append("\t\t\tdb.beginTransaction();\n");
				stringBuilder.append("\t\t\tdb.delete(\"" + tableName + "\", where, whereValues);\n");
				stringBuilder.append("\t\t\tdb.setTransactionSuccessful();\n");
				stringBuilder.append("\t\t}catch(Exception e){\n");
				stringBuilder.append("\t\t\te.printStackTrace();\n");
				stringBuilder.append("\t\t}finally{\n");
				stringBuilder.append("\t\t\tif(db!=null){\n");
				stringBuilder.append("\t\t\t\tdb.endTransaction();\n");
				stringBuilder.append("\t\t\t\tdb.close();\n");
				stringBuilder.append("\t\t\t}\n");
				stringBuilder.append("\t\t}\n");
				stringBuilder.append("\t}\n\n");

				// toObject方法
				stringBuilder.append("\tpublic static " + className + " toObject(Cursor cursor){\n");
				stringBuilder.append("\t\t" + className + " " + objName + " = new " + className + "();\n");
				if (columns != null && columns.size() >= 1) {
					for (int j = 0; j < columns.size(); j++) {
						Column column = columns.get(j);
						String columnName = column.getAttributes().get(ATTR_NAME);
						stringBuilder.append("\t\t" + objName + ".set" + firstUpperCase(columnName) + "(cursor.get");
						if (column.getJavaType().equals("byte[]")) {
							stringBuilder.append("Blob");
						} else {
							stringBuilder.append(firstUpperCase(column.getJavaType()));
						}
						stringBuilder.append("(cursor.getColumnIndex(\"" + columnName + "\")));\n");
					}
				}
				stringBuilder.append("\t\treturn " + objName + ";\n");
				stringBuilder.append("\t}\n\n");

				// toValues方法
				stringBuilder.append("\tpublic static ContentValues toValues(" + className + " " + objName + "){\n");
				stringBuilder.append("\t\tContentValues values = new ContentValues();\n");
				stringBuilder.append("\t\tif(" + objName + "!=null){\n");
				if (columns != null && columns.size() >= 1) {
					for (int j = 0; j < columns.size(); j++) {
						Column column = columns.get(j);
						String columnName = column.getAttributes().get(ATTR_NAME);
						stringBuilder.append("\t\t\tvalues.put(\"" + columnName + "\", " + objName + ".get" + firstUpperCase(columnName) + "());\n");
					}
				}
				stringBuilder.append("\t\t}\n");
				stringBuilder.append("\t\treturn values;\n");
				stringBuilder.append("\t}\n\n");

				stringBuilder.append("}\n");
				File accessFile = new File(accessFolder, accessClassName + ".java");
				fileWriter = new FileWriter(accessFile);
				fileWriter.write(stringBuilder.toString());
				fileWriter.flush();
				fileWriter.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取节点的所有属性
	 * 
	 * @param node
	 * @return
	 */
	public static Map<String, String> getAttributes(Node node) {
		Map<String, String> map = new HashMap<String, String>();
		if (node != null) {
			NamedNodeMap namedNodeMap = node.getAttributes();
			for (int i = 0; i < namedNodeMap.getLength(); i++) {
				Node attr = namedNodeMap.item(i);
				map.put(attr.getNodeName(), attr.getNodeValue());
			}
		}
		return map;
	}

	/**
	 * 根据name获取当前节点某一个属性的值
	 * 
	 * @param parser
	 * @param name
	 * @return
	 */
	public static String getValue(XmlPullParser parser, String name) {
		if (parser != null && name != null && !name.equals("")) {
			for (int i = 0; i < parser.getAttributeCount(); i++) {
				if (name.equals(parser.getAttributeName(i))) {
					return parser.getAttributeValue(i);
				}
			}
		}
		return "";
	}

	/**
	 * 将数据类型转换成Java类型
	 * 
	 * @param dataType
	 * @return
	 */
	public static String toJavaType(String dataType) {
		// 数据类型
		String javaType = null;
		if ("TEXT".equals(dataType)) {
			javaType = "String";
		} else if ("INTEGER".equals(dataType)) {
			javaType = "int";
		} else if ("REAL".equals(dataType)) {
			javaType = "float";
		} else if ("BLOB".equals(dataType)) {
			javaType = "byte[]";
		} else {
			javaType = "Object";
		}
		return javaType;
	}

	/**
	 * 获取字段的Java类型
	 * 
	 * @param columnName
	 * @param columns
	 * @return
	 */
	public static String getJavaType(String columnName, List<Column> columns) {
		if (columnName != null && !columnName.equals("") && columns != null && columns.size() >= 1) {
			for (int i = 0; i < columns.size(); i++) {
				if (columnName.equals(columns.get(i).getAttributes().get(ATTR_NAME))) {
					if (columns.get(i).getJavaType() == null) {
						return "Object";
					} else {
						return columns.get(i).getJavaType();
					}
				}
			}
		}
		return "Object";
	}

	/**
	 * 将原字符串首字母大写
	 * 
	 * @param source
	 * @return
	 */
	public static String firstUpperCase(String source) {
		String result = null;
		if (source != null && !source.equals("")) {
			if (source.length() == 1) {
				result = source.substring(0, 1).toUpperCase(Locale.getDefault());
			} else {
				result = source.substring(0, 1).toUpperCase(Locale.getDefault()) + source.substring(1);
			}
		} else {
			result = source;
		}
		return result;
	}

	/**
	 * 将原字符串首字母小写
	 * 
	 * @param source
	 * @return
	 */
	public static String firstLowerCase(String source) {
		String result = null;
		if (source != null && !source.equals("")) {
			if (source.length() == 1) {
				result = source.substring(0, 1).toLowerCase(Locale.getDefault());
			} else {
				result = source.substring(0, 1).toLowerCase(Locale.getDefault()) + source.substring(1);
			}
		} else {
			result = source;
		}
		return result;
	}

	/**
	 * 
	 * @param dbFilePath
	 *            数据库文件绝对路径
	 * @param xmlPath
	 *            数据库结构xml绝对路径
	 */
	public static void createDbByJDBC(String dbFilePath, String xmlPath) {
		File dbFile = new File(dbFilePath);
		if (dbFile.exists()) {
			dbFile.delete();
		}
		try {
			dbFile.createNewFile();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JtSqlite db = getDBbyDomParser(xmlPath);
		Connection connection = null;
		Statement statement = null;
		List<String> sqls = createSQL(db);
		try {
			Class.forName("org.sqlite.JDBC");
			connection = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
			connection.setAutoCommit(true);
			statement = connection.createStatement();
			statement.execute("CREATE TABLE IF NOT EXISTS android_metadata(locale TEXT)");
			for (int i = 0; i < sqls.size(); i++) {
				statement.execute(sqls.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (statement != null) {
					statement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		File file = new File("");
		System.out.println(file.getAbsolutePath());
		JtSqliteUtils.createClass(file.getAbsolutePath() + "/res/xml/cq.xml", file.getAbsolutePath() + "/src", "com.jingtuo.android.db");
	}

}

 

 

<?xml version="1.0" encoding="UTF-8"?>

<!ENTITY % datatypes "(TEXT|INTEGER|REAL|BLOB)">
<!ENTITY % constraints "(NOTNULL|NULL|UNIQUE|COLLATE|CHECK)">

<!ELEMENT db  ( table+ )>
<!ATTLIST db
name CDATA #REQUIRED
>

<!ELEMENT table  ( column+ , primary_key?, foreign_key? )>
<!ATTLIST table
name CDATA #REQUIRED
comment CDATA #IMPLIED
>

<!ELEMENT primary_key  EMPTY>
<!ATTLIST primary_key
column CDATA #REQUIRED
>

<!ELEMENT foreign_key  EMPTY>
<!ATTLIST primary_key
column CDATA #REQUIRED
>

<!ELEMENT column  EMPTY>
<!ATTLIST column
name CDATA #REQUIRED
datatype %datatypes; #REQUIRED
constraint %constraints; #IMPLIED
default CDATA #IMPLIED
comment CDATA #IMPLIED
>

 

 

使用步骤:

<1>使用DTD文件生成数据库xml文件。

<2>使用JtSqliteUtils类的createClass方法生成实体类

你可能感兴趣的:(android,类,sqlite,自定义xml,自定义DTD)