C# 操作Access資料庫

來源:互聯網
上載者:User

標籤:c#   access   

<pre name="code" class="csharp"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px; background-color: rgb(255, 255, 255);">                                                                                                           </span><span style="font-family: Arial, Helvetica, sans-serif; font-weight: normal; background-color: rgb(255, 255, 255);"><span style="font-size:24px;">c#  操作Access資料庫</span></span>
這兩天做項目,需要將資料存放區到Access資料庫中,並在DataGridView控制項中顯示出來。Access資料庫的文法與SQL的有所不同,在此總結一下資料庫的串連以及增刪改基本操作。在程式開始時,我打算使用一些資料庫動作陳述式來建立一個資料庫,不過好像用的不是很成功。而且如果要手動建立資料庫,則在啟動程式時,要判斷沒有某張表時,要建立該表。1.首先要串連資料庫:其中的SewWorkStation.accdb為項目中要用到的資料庫。
  public static string dbPath = System.Windows.Forms.Application.StartupPath + "\\SewWorkStation.accdb";        public string dbName = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+dbPath+";";        public OleDbConnection oleDbConn = null;        public DBOperate()        {            oleDbConn = new OleDbConnection(dbName);        }

2.用語句建立表:  
 public void CreateRobotTable( )        {            try            {                oleDbConn.Open();                string excuteStr = "Create Table t_Robot (rId int ,rName text,rIP text,rPort text)";                OleDbCommand oleDbComm = new OleDbCommand(excuteStr, oleDbConn);                oleDbComm.ExecuteNonQuery();            }            catch (Exception e)            {                MessageBox.Show(e.Message);            }            finally            {                oleDbConn.Close();            }        }
當然也可以在外部建立好資料庫建好表,然後在程式中只進行增刪改操作,這樣也不用檢查表是否存在了。大家可能看到我這裡建立表的屬性,與下面查詢時表的屬性不一致哈~,其實我是在外部建立好一個空的表的,這裡面只是記錄下文法啦。
在網上查到了一段代碼,判斷資料庫中是否存在某表,不過我執行了幾次,就是剛建立了表也找不到,dtTable中是空的,大家如果有什麼好的方法可以提醒我一下,。
  public bool VerifyTableInAccess( string TableName)        {            bool flag = false;            try            {                oleDbConn.Open();                DataTable dtTable = oleDbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, TableName });                if (dtTable == null)                {                    flag = false;                    return flag;                }                foreach (DataRow DRow in dtTable.Rows)                {                    if (DRow["TABLE_NAME"].ToString().Trim().ToUpper() == TableName.Trim().ToUpper())                    {                        flag = true;                        break;                    }                }            }            catch (Exception e)            {                MessageBox.Show(e.Message);                flag = false;            }            finally            {                oleDbConn.Close();            }            return flag;        }


3.預覽表 
public void ShowTable( string tableName,DataGridView dataGridView )        {            try            {                oleDbConn.Open();                DataSet dataSet = new DataSet();                OleDbDataAdapter adapter = new OleDbDataAdapter();                OleDbCommand command = new OleDbCommand("select * from " + tableName, oleDbConn);                adapter.SelectCommand = command;                adapter.Fill(dataSet);                dataGridView.DataSource = dataSet.Tables[0];            }            catch (Exception e)            {                MessageBox.Show(e.Message);            }            finally            {                oleDbConn.Close();            }        }
這裡面使用到了適配器OleDbDataAdapter,也可以使用OleDbDataReader來讀取。4.添加資料
  public void Insert(string  table, object obj )        {            string insertStr = "";                       try            {                oleDbConn.Open();                OleDbCommand oleDbComm = null;                switch (table)                {                    case "t_Robot":                        MRobot robot = (MRobot)obj;                        insertStr = "Insert into t_Robot(機器人編號,機器人名稱,機器人IP,機器人連接埠) Values(?,?,?,?)";                        oleDbComm = new OleDbCommand(insertStr, oleDbConn);                        oleDbComm.Parameters.AddWithValue("機器人編號", robot.Id);                        oleDbComm.Parameters.AddWithValue("機器人名稱", robot.Name);                        oleDbComm.Parameters.AddWithValue("機器人IP", robot.IP);                        oleDbComm.Parameters.AddWithValue("機器人連接埠", robot.Port);                        break;                    default:                        break;                }                if (!"".Equals(insertStr))                {                    oleDbComm.ExecuteNonQuery();                }            }            catch (Exception e)            {                MessageBox.Show(e.Message);            }            finally            {                oleDbConn.Close();            }       
這裡要添加資料,就需要參數化查詢的方式,使用OleDbCommand.Parameters這個屬性了。
5.刪除資料通過id來刪除資料,開始時使用了Access中自動的Id,但發現即使刪了一條資料後,後面資料的id沒有自動更新,如果再新添加一條資料,id是max(id)+1,這點要注意。
   public void Delete(string table,int id  )        {            string delStr = "";            string paramName = "";            try            {                switch(table)                {                    case "t_Robot":                          delStr = "Delete * from t_Robot where 機器人編號=?";                          paramName = "rId";                          break;                    default:                          break;                }                if(!"".Equals(delStr))                {                    oleDbConn.Open();                    OleDbCommand oleDbComm = new OleDbCommand(delStr, oleDbConn);                    oleDbComm.Parameters.AddWithValue(paramName, id);                    oleDbComm.ExecuteNonQuery();                }            }            catch (Exception e)            {                MessageBox.Show(e.Message);            }

6.更新id
 public void UpdateId(string table ,int id  )        {            string updateStr = "";            try            {                oleDbConn.Open();                OleDbCommand oleDbComm = null;                switch (table)                {                    case "t_Robot":                        updateStr = "update t_Robot set 機器人編號 = 機器人編號-1   where 機器人編號>@index";                        break;                    default:                        break;                }                if (!"".Equals(updateStr))                {                    oleDbComm = new OleDbCommand(updateStr, oleDbConn);                    oleDbComm.Parameters.AddWithValue("@index",id);                    oleDbComm.ExecuteNonQuery();                }            }            catch (Exception e)            {                MessageBox.Show(e.Message);            }            finally            {                oleDbConn.Close();            }               }
注意喔,上面的更新語句中是update  tableName set id = id -1 where id > delId ; 看到沒裡面沒有select...,Access的更新語句與sql的update語句不同。7.修改資料
   public void Update(string table ,object obj )        {            string updateStr = "";            try            {                oleDbConn.Open();                OleDbCommand oleDbComm = null;                switch (table)                {                    case "t_Robot":                        MRobot robot = (MRobot)obj;                        updateStr = "update t_Robot set 機器人名稱=?,機器人IP=?,機器人連接埠=? where 機器人編號=?";                        oleDbComm = new OleDbCommand(updateStr, oleDbConn);                        oleDbComm.Parameters.AddWithValue("機器人名稱", robot.Name);                        oleDbComm.Parameters.AddWithValue("機器人IP", robot.IP);                        oleDbComm.Parameters.AddWithValue("機器人連接埠", robot.Port);                        oleDbComm.Parameters.AddWithValue("機器人編號", robot.Id);                        break;                    default:                        break;                }                if(!"".Equals(updateStr))                {                  oleDbComm.ExecuteNonQuery();                }            }            catch (Exception e)            {                MessageBox.Show(e.Message);            }            finally            {                oleDbConn.Close();            }               }



C# 操作Access資料庫

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.