INSERT XML Files Into Databases Using XML2OL2OL2OLDB

xiaoxiao2021-03-06  136

Introduction to Xml2OleDb [Download Code] Have you ever wanted to add your XML data files into a database? Xml2OleDb will demonstrate how easy ASP.NET makes it to add XML data to any OleDb database including SQL Server, Access, Excel, Visual FoxPro, FoxPro, and dBase. XML is definitely the best way to share data via the World Wide Web. XML data can easily be integrated into web applications for many uses. However, at some point you (or someone you work for) will want XML data added to a database. Hopefully this will be an easy task for you by the time you finish reading this article and looking at the code sample. Now let's get started. The first step is to load the XML file into a DataSet and get the first table. This table is the DataTable we will be adding to the database. Next remove the extension from the XML file. The file name minus the extension will be used as the table name in the database. An error message will be displayed if the XML File is not in The Proper Format. Look At THE AUTHORS.XML FILE INCLUDE in The Download To See The Proper File Into A Dataset Using The

// File Name Submitted from the Web Form

DataSetXml.readxml (httpContext.current.server.mappath (TextBoxxml.Text));

// Get the first table in the dataset

DataTableXML = DataSetXml.tables [0];

// Remove the extension from the xml file. The file name minus

// The extension will be used as the table name in the database.

tableName = textBoxXml.Text.Substring (0, textBoxXml.Text.Length -4); Once the XML file has been loaded, check to see if the DataTable contains any data (rows) Next call two routines:. the first checks to see if the table exists in the database and creates the table if it does not exist, and the second inserts the data from the XML file into the database. Finally, if there were no errors, display a message stating that the XML file was successfully inserted INTO the DATABASE. // Check To See if Table One Contains Any Data (ROWS) IF (DataTableXML.Rows.count> 0)

Creating the Database TableThis next routine checks to see if the table exists in the database and creates the table if it does not exist. Start by creating an OleDb database connection using the connection string provided when the web form is submitted. Open the database connection and retrieve database schema information for only the table we are looking for and place it in a DataTable. in this example the table name is the name of the XML file without the extension.// Create an OleDb database connection using the connection string

// provided when the Web Form Is Submitted

OLEDBCONNECTION OLEDBCONN = New OLEDBCONNECTION (TextBoxoledb.text);

// Open the Database Connection

OLEDBCONN.OPEN ();

// Retrieve Database Schema Information for Only The Table We Are Looking for

// and place it in a datatable.

// in this example the table name is the name of the xml file without the extension

DataTable Schematable =

OLEDBCONN.GETOLEDBSCHEMATABLE (OLEDBSChemAGUID.TABLES,

new object [] {null, null, tableName, "TABLE"});. Using the DataTable that contains the database schema check to see if the table exists If the table exists in the schema there will be one row in the DataTable If. the table does not exist in the schema, the DataTable row count will be zero.// Check to see if the table exists in the database schema // If the table exists in the schema there will be row 1 in the DataTable

// if the table not exist in the schema the datatable row count will be zero

if (schemaTable.Rows.Count <1) If the table does not exist in the database, create it. Make the create table SQL command by iterating through the XML file's columns. This way the database columns will have the same name as the XML file. In this example we create all columns as CHAR (text / string) data type with a length of 100. This simplifies the code, because not all data types are supported by all OleDb databases. Once the SQL command is created, it is Executed Against the Database Using The ExecutenonQuery Method of the Oledbcommand./ Make The Create Table SQL Command by Iterating THROUGH THE XML FILE'S

// Column. this Way The Database Columns Will Have The Same Name as the xml file.

Sqlcmd = "CREATE TABLE" TABLENAME "(";

For (int i = 0; i

{

// this Adds Each Column As A TEXT / STRING TYPE WITH A Length of 100

SQLCMD = SQLCMD DataTableXML.COLUMNS [i] .Columnname.tostring () "

CHAR (100), ";

}

// Remove the last ","

Sqlcmd = sqlcmd .substring (0, sqlcmd.length - 1) ");";

// Create and Execute The Create Table Command

OLEDBCOMMAND OLEDBCMD = New OLEDBCOMMAND (SQLCMD, OLEDBCONN); OLEDBCMD.ExecutenonQuery ();

Adding the XML Data to the Database [Download Code] Now that we know the database has a table that can hold the XML file we start inserting records. Again we create and open an OleDbConnection to the database and iterate through the rows in the DataTable from the XML file, creating a SQL insert command for each row of data. Do this by iterating through the DataTable columns to get the column names and values ​​for the current row. Finally, use the OleDbCommand ExecuteNonQuery method to insert each row into the database. // iperate rows in the dataatable

Foreach (DataRow Dr in DataTableXML.ROWS)

{

// Create the SQL Insert Command for Each Row

String Sqlcmd = "Insert INTO [" TableName "] (";

// iperate the datatable columns

For (int i = 0; i

{

// add the colorn name

SQLCMD = SQLCMD DATATABLEXML.COLUMNS [i] .Columnname.toString () ","

}

Sqlcmd = sqlcmd.substring (0, sqlcmd.length - 1) ") VALUES (";

// iperate the datatable columns

For (int x = 0; x

{

// add the colorn value for this row

SQLCMD = SQLCMD "'" DR [x] .tostring (). Replace ("'", "'") ";"

}

Sqlcmd = sqlcmd.substring (0, sqlcmd.length - 1) ");";

// Create and Execute the Insert Command

OLEDBCommand OLEDBCMD = New OLEDBCOMMAND (SQLCMD, OLEDBCONN);

OLEDBCMD.EXECUTENONQUERY ();

}

Code Sample Instructions and Conculsion Now let's discuss using the sample code. Place all of the files from the download into a virtual directory. You do not need to compile the source, because I have included the assembly (.dll) file in the download. This sample creates tables in databases, but it does not create the database. You will need to create the database before adding XML data to it. I have included an empty Access database (Database.mdb) and an empty Excel database / workbook (Database .xls) for you to use. you need to give the ASP.NET process account (default is MACHINENAME / ASPNET) write permissions on the database file. for FoxPro / dBase this could be just an empty directory.Navigate to the virtual directory you Created. Enter the name of the xml file (Must Be in the Same Virtual Directory). Don't Enter The Path, Just The File Name (Authors.xml). I Have Included A Sample XML File (Authors.xml) That you CAN use. next, enter the oledb connection string and click the submit butt ON.

Example Connection Strings: Access: provider = microsoft.jet.Oledb.4.0; data source = c: /data/database.mdb; Excel: provider = microsoft.jet.Oledb.4.0; data source = c: / data / data. 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 =;

When I started thinking about writing this article I imagined that code would be very complicated. I was very pleased to find out how few lines of code it took. That's how easy ASP.NET makes it to add XML data into the OleDb database of your CHOICE.

转载请注明原文地址:https://www.9cbs.com/read-127431.html

New Post(0)