我有一个存储多个值的类。目前我列出了对象然后使用它们,但现在我必须迁移到Access数据库。有人能告诉我是否可以将这些对象放入数据库中?
答案 0 :(得分:1)
您可以将对象序列化为XML,然后将其写入Memo
字段(在Access 2013中称为Long Text
字段)。以下代码适用于我:
public class MyClass
{
public string Name { get; set; }
public List<string> FavoriteThings { get; set; }
}
class Program
{
static void Main(string[] args)
{
var myObject = new MyClass();
myObject.Name = "Gord";
var myFavs = new List<string>();
myFavs.Add("bicycles");
myFavs.Add("ham");
myObject.FavoriteThings = myFavs;
var xs = new System.Xml.Serialization.XmlSerializer(myObject.GetType());
var sw = new System.IO.StringWriter();
xs.Serialize(sw, myObject);
using (var con = new OleDbConnection())
{
con.ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=C:\Users\Public\Database1.accdb;";
con.Open();
using (var cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandText = "INSERT INTO tblObjects (ObjectID, ObjectXML) VALUES (?,?)";
cmd.Parameters.AddWithValue("?", 1);
cmd.Parameters.AddWithValue("?", sw.ToString());
cmd.ExecuteNonQuery();
}
con.Close();
}
}
}
当我打开Access表格时,选择备注字段,然后按 Shift F2 到&#34;放大&#34;我看到了