使用xml檔案,做資料的匯入,匯出 (轉)

amyz發表於2007-08-15
使用xml檔案,做資料的匯入,匯出 (轉)[@more@]

的dataset是一個很有趣的,藉助與可以很快捷的做出資料匯入,匯出功能.microsoft-com::office" />

關鍵程式碼如下:

///

  /// export the table of database

  ///

  /// table name

  /// file path

  /// Connection of database

  ///

  public bool ExportTableToXml(string m_TableName,string m_FilePath,OleConnection m_PubConn)

  {

  try

  {

  DataSet ds = new DataSet();

  OleDbDataAdapter m_Adapter = new OleDbDataAdapter("",m_PubConn);

  m_Adapter.Command  = new OleDbCommand("select * from "+m_TableName,m_PubConn);

  m_Adapter.Fill(ds,m_TableName);

  System.IO.FileStream fs  = new System.IO.FileStream(m_FilePath,System.IO.FileMode.Create);

  ds.WriteXml(fs, XmlWriteMode.WriteSchema);  

  fs.Close();

  return true;

  }catch (System.Exception error)

  {

    MessageBox.Show(error.Message,"error",MessageBoxButtons.OK,MessageBoxIcon.Error);

  return false;

    }

  }

  ///

  /// import the xml file to database

  ///

  /// file path

  /// table name

  /// connection of database

  ///

  public bool ImportXmlToTable(string m_FilePath,string m_TableName,OleDbConnection m_PubConn)

  {

  try

  {

  DataSet ds  = new DataSet();

  DataSet mdsMain  = new DataSet();

  OleDbCommand m_Comm  = new OleDbCommand("",m_PubConn);

  OleDbDataAdapter m_Adapter = new OleDbDataAdapter();

  mdsMain.ReadXml(m_FilePath,XmlReadMode.ReadSchema); 

  //delete from tablename

  m_Comm.CommandText  = "delete from "+m_TableName;

  m_Comm.ExecuteNonQuery();

  //set the m_Adapter

  m_Comm.CommandText  = "select * from "+m_TableName;

  m_Adapter.SelectCommand  = m_Comm;

  OleDbCommandBuilder cb  = new OleDbCommandBuilder(m_Adapter);

  m_Adapter.Fill(ds,m_TableName); 

  System.IO.MemoryStream ms = new System.IO.MemoryStream();

  mdsMain.WriteXml(ms, XmlWriteMode.DiffGram);

  ms.Seek(0, SeekOrigin.Begin);

  ds.ReadXml(ms, XmlReadMode.DiffGram);

  m_Adapter.Update(ds, m_TableName);

  ds.AcceptChanges(); 

  ms.Close();

  return true;

    }catch(System.Exception error)

  {

  MessageBox.Show(error.Message.ToString(),"error",MessageBoxButtons.OK,MessageBoxIcon.Error);

  }

   

  return false;

  }

  }

測試程式碼:

private void button1_Click( sender, System.EventArgs e)

  {

   

    ExportTableToXml("T_FieldSet","c:xx.xml",m_PubConn);

  ExportTableToXml("T_FieldItem","c:yy.xml",m_PubConn);

  MessageBox.Show("success");

  }

  private void button2_Click(object sender, System.EventArgs e)

  {

 

 

  ImportXmlToTable("c:xx.xml","T_FieldSet",m_PubConn);

  ImportXmlToTable("c:yy.xml","T_FieldItem",m_PubConn);

  MessageBox.Show("success");

 

 

  }

注意:

1.  我在匯入資料的時候,將原來的資料刪除了的;

2.  2個匯入,匯出只是針對單個表;


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752019/viewspace-959006/,如需轉載,請註明出處,否則將追究法律責任。

相關文章