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的文件夾