Home > DeveloperSection > Forums > Insert data from XML to database in C#
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    June-15-2013 5:20 AM

 C# C# 
Ratings:


 1 Reply(s)
 1976  View(s)
Rate this:
Hi Developers,

How to insert data from XML to database?

Thanks in advance.



Sumit Kesarwani

Total Post:378

Points:2694
Posted on    June-15-2013 7:16 AM

Hi Pravesh,

You can use this code:

using System;

using System.Data;

using System.Windows.Forms;

using System.Xml;

using System.Data.SqlClient;

 

namespace WindowsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            string connetionString = null;

            SqlConnection connection;

            SqlCommand command;

            SqlDataAdapter adpter = new SqlDataAdapter();

            DataSet ds = new DataSet();

            XmlReader xmlFile;

            string sql = null;

 

            int product_ID = 0;

            string Product_Name = null;

            double product_Price = 0;

 

            connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";

 

            connection = new SqlConnection(connetionString);

 

            xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());

            ds.ReadXml(xmlFile);

            int i = 0;

            connection.Open();

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)

            {

                product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);

                Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();

                product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);

                sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";

                command = new SqlCommand(sql, connection);

                adpter.InsertCommand = command;

                adpter.InsertCommand.ExecuteNonQuery();

            }

            connection.Close();

            MessageBox.Show("Done .. ");

        }

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick