The Xml data type is introduced in SQL server2005 and later SQL server. To use the Xml data type in C #, you must specify the parameter type as SqlDbType, and use SqlXml for the parameter value type, as shown in the following example:
Suppose there is A type of table A. Table A has two fields: ID type int and Data Type Xml. I want to use C # To insert A row of records into the table:
Copy codeThe Code is as follows: static void InsertA (int aid, string contentXml)
{
// ConnString is the connection string and needs to be defined additionally
Using (SqlConnection conn = new SqlConnection (ConnString ))
{
Conn. Open ();
String SQL = "INSERT INTO [A] ([ID], [Content]) VALUES (@ id, @ content )";
Using (SqlCommand comm = new SqlCommand (SQL, conn ))
{
Using (XmlTextReader rdr = new XmlTextReader (contentXml, XmlNodeType. Document, null ))
{
SqlXml sqlXml = new SqlXml (rdr );
SqlParameter parmID = new SqlParameter ("@ id", aid );
SqlParameter parmContent = new SqlParameter ("@ content", SqlDbType. Xml, sqlXml. Value. Length );
ParmContent. Value = sqlXml;
Comm. Parameters. Add (parmID );
Comm. Parameters. Add (parmContent );
Comm. ExecuteNonQuery ();
}
}
Conn. Close ();
}
}
When inserting data, you must use the SqlXml data type as the parameter value, but the C # data type when reading Xml data is string. Example:Copy codeThe Code is as follows: string GetContent (int id)
{
String SQL = "SELECT [Content] FROM [A] WHERE [ID] =" + id;
Using (SqlConnection conn = new SqlConnection (ConnString ))
{
Conn. Open ();
Using (SqlCommand comm = new SqlCommand (SQL, conn ))
{
String xml = (string) comm. ExecuteScalar ();
Return xml;
}
}
}
Note that when inserting data, the parameter value type of the Xml field cannot be string. If you use string directly, an Encoding Error is returned.