xml2oledb简介
xml是互联网共享数据的最好的方法,xml格式的数据可以很轻松的集成到不同的web应用中去。但如果你想将xml文件插入到数据库,怎么办?xml2oledb将向您说明往oledb数据库,比如sql server, access, excel, visual foxpro, foxpro, and dbase等插入xml文件的数据是如何轻松。
首先,将xml文件装载进dataset,并得到第一个表,这个表就是我们要加入到数据库的datatable;接下来,去除xml文件的扩展名,文件名字去掉扩展名将是我们数据库中使用的表名。如果xml格式不准确,将会报告错误,源代码中有xml文件格式的例子。参见authors.xml
// 装载我们提交的xml文件到dataset
datasetxml.readxml(httpcontext.current.server.mappath(textboxxml.text));
// 得到dataset中的第一个表
datatablexml = datasetxml.tables[0];
// 生成表名
tablename = textboxxml.text.substring(0,textboxxml.text.length -4);
一旦xml装载成功,首先检查数据表是否有数据(rows),接下来检查数据库是否存在表,如果不存在就创建一个;然后将数据从xml插入到数据库中。
// 检查是否有数据存在(rows)
if(datatablexml.rows.count > 0)
创建数据库表
创建数据库连接,得到我们要添加表的数据库架构信息。
// 创建数据库连接,打开数据库,得到数据库表的架构信息
oledbconnection oledbconn = new oledbconnection(textboxoledb.text);
oledbconn.open();
datatable schematable =
oledbconn.getoledbschematable(oledbschemaguid.tables,
new object[] {null, null, tablename, "table"});
// 检查表是否存在,如果存在在datatable中将有一条记录
if(schematable.rows.count < 1)
sqlcmd = "create table " + tablename + " (";
for(int i = 0;i < datatablexml.columns.count;i++)
{
// 添加列text/string type 长度 100
sqlcmd = sqlcmd + datatablexml.columns[i].columnname.tostring() + " char(100),";
}
sqlcmd = sqlcmd .substring(0,sqlcmd.length - 1) + ");";
oledbcommand oledbcmd = new oledbcommand(sqlcmd,oledbconn);
oledbcmd.executenonquery();
添加xml数据到数据库
// 遍历datatable中的rows
foreach(datarow dr in datatablexml.rows)
{
string sqlcmd = "insert into [" + tablename + "] (";
// 遍历datatable的列
for(int i = 0;i < datatablexml.columns.count;i++)
{
// 添加column name
sqlcmd = sqlcmd + datatablexml.columns[i].columnname.tostring() + ",";
}
sqlcmd = sqlcmd.substring(0,sqlcmd.length - 1) + ") values (";
// 遍历 datatable columns
for(int x = 0;x < datatablexml.columns.count;x++)
{
// 添加column value到row
sqlcmd = sqlcmd + "'" + dr[x].tostring().replace("'","''") + "',";
}
sqlcmd = sqlcmd.substring(0,sqlcmd.length - 1) + ");";
oledbcommand oledbcmd = new oledbcommand(sqlcmd,oledbconn);
oledbcmd.executenonquery();
}
注意的问题:
测试时先下载源代码,创建一个空的数据库,设置可修改权限database.mdb,database.xls,对foxpro/dbase 创建空目录
连接字符串例子:
access: provider=microsoft.jet.oledb.4.0;data source=c:\data\database.mdb;
excel: provider=microsoft.jet.oledb.4.0;data source=c:\data\database.xls;extended properties=excel 8.0;
foxpro/dbase: provider=microsoft.jet.oledb.4.0;data source=c:\data;extended properties=dbase iv;
sql server: provider=sqloledb; data source=localhost; initial catalog=database;user id=sa;password=;
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器