iT邦幫忙

0

SQL 連續插入/編輯

Ray 2020-12-03 16:50:382323 瀏覽
  • 分享至 

  • xImage

最近練習資料庫(Access)時遇到一個問題

當使用sql語句插入或編輯單一資料時,可以正常運作;
但插入/編輯多筆資料時,會發生資料表鎖定的情形

code:

public bool Query(string sql,string constr)
{
    try
    {
    //連接資料庫
     OleDbConnection con = new OleDbConnection(constr);
     con.Open();

     OleDbCommand cmd = new OleDbCommand
     {
      CommandText = sql,
      Connection = con
     };
     OleDbDataReader rd = cmd.ExecuteReader();
     return true;             
     }
     catch (Exception ex) { MessageBox.Show(ex.Message);return false;}
}
//插入單一資料
string sql="insert into Table (Column1,Column2) values('1','2')";   Query(sql, constr);

//插入多筆
for(int i=0;i<100;i++)
{
  string sql="insert into Table (Column1,Column2) values('1','2')";
  Query(sql, constr);
}

請問有什麼解決方法嗎?

看更多先前的討論...收起先前的討論...
我會換MSSQL進階資料庫@@..Access是簡易資料庫不太好用..
Ray iT邦新手 5 級 ‧ 2020-12-03 17:20:26 檢舉
謝謝建議,目前先從簡易的著手,有想說之後要換其他資料庫
ckp6250 iT邦好手 1 級 ‧ 2020-12-03 19:49:04 檢舉
我也認同純大大的說法,
若是初學,不要浪費時間在 Access 上,不值得。
等你習慣了想改就是一大篇的事了
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
rogeryao
iT邦超人 8 級 ‧ 2020-12-03 16:58:15
最佳解答
    try
    {
    //連接資料庫
     OleDbConnection con = new OleDbConnection(constr);
     con.Open();

     OleDbCommand cmd = new OleDbCommand
     {
      CommandText = sql,
      Connection = con
     };
     OleDbDataReader rd = cmd.ExecuteReader();
     //
     con.Close();
     //
     return true;             
     }
看更多先前的回應...收起先前的回應...
Ray iT邦新手 5 級 ‧ 2020-12-03 17:18:55 檢舉

奉上解答
另外想請問為何沒加此行時,會有部分資料可以新增

rogeryao iT邦超人 8 級 ‧ 2020-12-03 17:36:19 檢舉

基本上使用 con.Open(); 連接資料庫執行完 SQL 後就需 con.Close(); 來終止連線否則就會發生資料表鎖定的情形.
實務上針對同一資料表連線一次就可以了 ,你的 Function 最好在調整一下.

Ray iT邦新手 5 級 ‧ 2020-12-04 09:09:54 檢舉

好的 感謝

PPTaiwan iT邦好手 1 級 ‧ 2020-12-04 10:32:18 檢舉

OleDbConnection con = new OleDbConnection(constr);

要不要提到 Try 上一層, con.Close(); 包在 try finally ,try 內層發生程式錯誤 con.Close() 這部份也執行不到..

我要發表回答

立即登入回答