package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Demo {
static Map<String, String> coloumMap = new HashMap<String, String>();
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException, SQLException,
DocumentException {
SAXReader sax = new SAXReader();// 创建一个SAXReader对象
Document document = sax.read("src/info.xml");// 获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root = document.getRootElement();// 获取根节点
getNodes(root);// 从根节点开始遍历所有节点
conDB();
}
/**
* 数据库连接
*/
public static void conDB() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();// 加载驱动
Connection conn = DriverManager
.getConnection("jdbc:derby:TESTDB;create=true");// 连接数据库
Statement st = conn.createStatement();
String sqlString = "";
String colString = "";
for (String string : coloumMap.keySet()) {
sqlString += string + " " + coloumMap.get(string) + ",";
colString += string + ",";
}
sqlString = sqlString.substring(0, sqlString.length() - 1);
colString = colString.substring(0, colString.length() - 1);
sqlString = "(" + sqlString + ")";
colString = "(" + colString + ")";
st.execute("create table INFO2" + sqlString);// 建表
st.executeUpdate("insert into INFO2" + colString
+ " values ('hello','kitty')");// 插入数据
st.executeUpdate("insert into INFO2" + colString
+ "values ('你好','小猫')");// 插入数据
ResultSet rs = st.executeQuery("select * from INFO2");// 读取刚插入的数据
while (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
System.out.println("ID=" + id);
System.out.println("NAME=" + name);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从指定节点开始,递归遍历所有子节点
*/
public static void getNodes(Element node) {
if (node.getName().equals("元素")) {
List<Attribute> listAttr = node.attributes();// 当前节点的所有属性的list
String key = null;
String value = null;
for (Attribute attr : listAttr) {// 遍历当前节点的所有属性
if (attr.getName().equals("元素字典名称")) {
key = attr.getValue();
}
if (attr.getName().equals("元素单位")) {
value = attr.getValue();
if (value.equals("字节")) {
value = "VARCHAR(50)";
}
}
}
coloumMap.put(key, value);
}
// 递归遍历当前节点所有的子节点
List<Element> listElement = node.elements();// 所有一级子节点的list
for (Element e : listElement) {// 遍历所有一级子节点
getNodes(e);// 递归
}
}
}
运行以后输出
ID=hello
NAME=kitty
ID=你好
NAME=小猫
项目中需要添加derby.jar和dom4j.jar
在项目下会生成一个TESTDB的文件夹