Quantcast
Channel: Chanmingman's Blog
Viewing all articles
Browse latest Browse all 1938

Insert XML to MS SQL Server XML Column

$
0
0

This blog article shows you how to insert a XML file into MS SQL Server XML column. The code snippet below writes to the XML column in SQL Server database table.

static void Main(string[] args)
{
     string xmlFilePath = “XMLFileRemoveUTF8.xml”;
     string connectionString = “Server=.;Database=poc;Integrated Security=True;TrustServerCertificate=true”;
     int id = 1;
     // Read the XML file
     string xmlContent = File.ReadAllText(xmlFilePath);
     // Insert the XML into the database
     using (SqlConnection connection = new SqlConnection(connectionString))
     {
         connection.Open();
         string query = “INSERT INTO tblMyXml (id, MyXml) VALUES (@id, @xml)”;
         using (SqlCommand command = new SqlCommand(query, connection))
         {
             command.Parameters.AddWithValue(“@id”, id);
             command.Parameters.AddWithValue(“@xml”, xmlContent);
             command.ExecuteNonQuery();
         }
     }
     Console.WriteLine(“XML inserted into the database successfully.”);
}

Also: Convert SqlDataReader to Json

clip_image002

Source code download: https://github.com/chanmmn/database/tree/main/2024/ConAppWriteXMLSql?WT.mc_id=DP-MVP-36769

Reference: https://learn.microsoft.com/en-us/sql/t-sql/xml/query-method-xml-data-type?view=sql-server-ver16?WT.mc_id=DP-MVP-36769

https://learn.microsoft.com/en-us/sql/t-sql/xml/value-method-xml-data-type?view=sql-server-ver16?WT.mc_id=DP-MVP-36769


Viewing all articles
Browse latest Browse all 1938

Latest Images

Trending Articles



Latest Images