我之前写了一个,不过是把XML文件内容存入SQL Server中。起初webservice的参数是XMLDocument,结果他们用j2ee开发的,把参数改成了string。其实就是把xml文件读成string,我这边再还原一下。核心就是datatable->datatable column->sql。下面贴代码:private void TableInsert() { OleDbConnection oledbConn = new OleDbConnection(textBoxOleDb.Text); try { // Open the database connection oledbConn.Open(); // Iterate rows in the dataset foreach(DataRow dr in dataTableXml.Rows) { // Create the sql insert command for each row string sqlCmd = "insert into [" + tableName + "] ("; // Iterate the datatable columns for(int i = 0;i < dataTableXml.Columns.Count;i++) { // Add the column name sqlCmd = sqlCmd + dataTableXml.Columns[i].ColumnName.ToString() + ","; } sqlCmd = sqlCmd.Substring(0,sqlCmd.Length - 1) + ") values ("; // Iterate the datatable columns for(int x = 0;x < dataTableXml.Columns.Count;x++) { // Add the column 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(); } } catch { // If there are errors you will get this message Message.Text = "There was an error adding the XML data to the table."; } finally { // Close the database connection oledbConn.Close(); } }
{
OleDbConnection oledbConn = new OleDbConnection(textBoxOleDb.Text);
try
{
// Open the database connection
oledbConn.Open();
// Iterate rows in the dataset
foreach(DataRow dr in dataTableXml.Rows)
{
// Create the sql insert command for each row
string sqlCmd = "insert into [" + tableName + "] (";
// Iterate the datatable columns
for(int i = 0;i < dataTableXml.Columns.Count;i++)
{
// Add the column name
sqlCmd = sqlCmd + dataTableXml.Columns[i].ColumnName.ToString() + ",";
}
sqlCmd = sqlCmd.Substring(0,sqlCmd.Length - 1) + ") values (";
// Iterate the datatable columns
for(int x = 0;x < dataTableXml.Columns.Count;x++)
{
// Add the column 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();
}
}
catch
{
// If there are errors you will get this message
Message.Text = "There was an error adding the XML data to the table.";
}
finally
{
// Close the database connection
oledbConn.Close();
}
}