Go deep into the usage of SqlDbType. Xml type parameters in C #

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.