我將類型爲DataTable的對象保存到類型爲varbinary的字段中的SQL 2005數據庫中。我想恢復它,但我無法輸入它。這是我如何保存它。將byte []數組轉換爲DataTable
MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);
sw.Write(dt);
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Tables(TableName, TableData, QuestionID) VALUES (@TableName, @TableData, @QuestionID)", con))
{
cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = "a new table";
cmd.Parameters.Add("@TableData", SqlDbType.VarBinary,Int32.MaxValue).Value = memStream.GetBuffer();
cmd.Parameters.Add("@QuestionID", SqlDbType.VarChar).Value = "2";
cmd.ExecuteNonQuery();
}
'dt'是DataTable對象實例。
什麼用的STRIG 'S' 的? – 2009-08-19 14:36:43
@Ahmad:在這個例子中,一個DataTable被序列化爲一個byte [],然後編碼爲一個UTF8字符串,然後返回byte [],然後DataTable。由於您將字節存儲在數據庫中,因此無關緊要,但是如果您想將其作爲ntext存儲或將其插入到XML中,這將是您如何做到的。 – MyItchyChin 2009-08-19 15:05:54