简体   繁体   English

如何在C#中从SQL Server 2005检索xml?

[英]How to retrieve xml from SQL Server 2005 in C#?

I have inserted xml into SQL Server 2005 through rich text field successfully, now what I want to do is retrieve the xml from the DB but values separately and schema seperate... how can i do that in my existing code?? 我已经通过富文本字段成功地将xml插入SQL Server 2005,现在我要做的是从数据库中检索xml,但将值和模式分别分开...如何在现有代码中做到这一点?

public void setData()
{
   dc.ID = textBox1.Text;
   dc.Name = richTextBox1.Text;
}

private void button1_Click(object sender, EventArgs e)
{
    setData();

    int flag = db.InsertData("insert into xmlTB values('" + dc.ID + "','" + dc.Name + "')");
    if (flag > 0)
       MessageBox.Show("Record Added");
    else
       MessageBox.Show("Not Added");

    try
    {
    }
    catch (Exception ex) 
    {
        MessageBox.Show(ex.Message);
    }
}

where the remain code of insertion is in a separate class: 其余的插入代码位于单独的类中:

public SqlConnection conn = new SqlConnection("Data Source=SERVER1\\SQLEXPRESS;Initial Catalog=xml;Integrated Security=True;Pooling=False");

public int flag = 0;
public SqlDataReader sdr = null;
public DBConnection() { } // constructor

public int InsertData(string qry)
{
     try
     {
          conn.Open();
          SqlCommand cmd = new SqlCommand(qry, conn);
          flag = cmd.ExecuteNonQuery();
          conn.Close();
          return flag;
      }
      catch (Exception)
      {
          return flag;
      }
 }

thanks a lot 非常感谢

Several things you should definitely start using: 您肯定应该开始使用的几件事:

  • use parametrized queries for inserting values into your tables 使用参数化查询将值插入表中
  • use a specific list of columns in your INSERT statement - otherwise, next time that table changes, your INSERT will fail 在INSERT语句中使用特定的列列表 -否则,下次表更改时,INSERT将失败

The way you do it today is both fragile / brittle and will break when your table changes, plus the concatenating together of your SQL command is a great opportunity for SQL injection attacks. 今天的操作方式既脆弱又脆弱,并且在表更改时会破裂,再加上SQL命令的连接,这是进行SQL注入攻击的绝佳机会。 Just don't do it that way! 只是不要那样做!

So your first method should look something like this: 因此,您的第一种方法应如下所示:

private void button1_Click(object sender, EventArgs e)
{
    setData();

    string query = "INSERT INTO dbo.xmlTB(ID, Name) VALUES(@ID, @Name)";

    int flag = db.InsertData(query, ...(somehow pass in the parameters!.....);
    ......    
}

Secondly, your second method should 其次,第二种方法应该

  • use the using(....) { ... } constructs to protect and dispose your SqlConnection and SqlCommand object instances 使用using(....) { ... }结构来保护和处置您的SqlConnectionSqlCommand对象实例
  • do retrieve the XML from the database, use a simple SELECT query and call either ExecuteReader or ExecuteScalar on your SqlCommand object. 确实要从数据库中检索XML,请使用简单的SELECT查询并在SqlCommand对象上调用ExecuteReaderExecuteScalar

Something like this: 像这样:

public string ReadXmlData(int ID)
{
   string query = "SELECT XmlContent FROM dbo.xmlTB WHERE ID = @ID";
   string connectionString = "Data Source=SERVER1\\SQLEXPRESS;Initial Catalog=xml;Integrated Security=True;Pooling=False";

   using(SqlConnection conn = new SqlConnection(connectionString))
   using(SqlCommand cmd = new SqlCommand(query, conn))
   {
      cmd.Parameters.Add("@ID", SqlDbType.Int);
      cmd.Parameters["@ID"].Value = ID;

      conn.Open();
      string xmlContents = cmd.ExecuteScalar().ToString();
      conn.Close();

      return xmlContents;
   }
   catch (Exception)
   {
       return flag;
   }
}

The question appears vague but: After record added, call another method called say "GetData" (you'll need to write this). 这个问题看起来很模糊,但是:在添加记录后,调用另一个称为“ GetData”的方法(您需要编写此方法)。 This method might use cmd.ExecuteReader() to call the db. 此方法可能使用cmd.ExecuteReader()来调用数据库。 Ensure that your select statement in your query has "FOR XML" at the end of the table name. 确保查询中的select语句在表名的末尾具有“ FOR XML”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM