在数据库中插入列表

时间:2011-12-29 00:10:42

标签: c# winforms ms-access-2010

我在richtextbox ex中有一个列表:

dogs
cats 
books
other

如何插入表“动物”,列“家”一行?

1 个答案:

答案 0 :(得分:1)

使用ODBC

这样的事情
string connectionString ="yourConnectionString"
using (DbConnection conn = new OdbcConnection(connectionString))
using (DbCommand cmd = conn.CreateCommand())
{
  cmd.CommandText = "INSERT INTO Animals(home) VALUES (@animal)";
  DbParameter p = cmd.CreateParameter();
  p.ParameterName = "@animal";
  cmd.CommandType = CommandType.Text;
  conn.Open();
  using (DbTransaction tran = conn.BeginTransaction())
 {
     cmd.Transaction = tran;
     try
     {
         foreach (string line in MyRichTextBox.Lines)
         {
            p.Value = line;
            cmd.ExecuteNonQuery();
         }
         tran.Commit();
         conn.Close();
     }
     catch (Exception e)
     {
         tran.Rollback();
        throw(e);
     }
 }

}