access:版本2003(后綴.mdb,新版access可另存為2003兼容版)
using:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
打開數據庫:
string Con = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\Users\87627\Desktop\Database1.mdb";//第二個參數為文件的路徑
OleDbConnection dbconn = new OleDbConnection(Con);
dbconn.Open();//建立連接
OleDbDataAdapter inst = new OleDbDataAdapter("SELECT *FROM student", dbconn);//選擇全部內容
DataSet ds = new DataSet();//臨時存儲
inst.Fill(ds);//用inst填充ds
dataGridView1.DataSource = ds.Tables[0];//展示ds第一張表到dataGridView1控件
dbconn.Close();//關閉連接
增加操作:利用insert方法,在dbconn.Open();后添加以下代碼,然后將所有代碼復制到對應按鈕的click事件下
string Insert = "INSERT INTO student(studentName,age,tall,gender) values('" + "學生4" + "','" + 21 + "','" + 175 + "','" + "男" + "')";
//insert into 表名(字段1,字段2...)values('字段一內容','字段二內容'),上一行+用於字符串的連接,如果想用textBox傳值,可用
//string s = "'" + textBox1.Text + "'", x = "'" + textBox2.Text + "'";
OleDbCommand myCommand = new OleDbCommand(Insert, dbconn);//執行命令
myCommand.ExecuteNonQuery();//更新數據庫,返回受影響行數;可通過判斷其是否>0來判斷操作是否成功
刪除操作:利用delete方法,在dbconn.Open();后添加以下代碼,然后將所有代碼復制到對應按鈕的click事件下
string s = "'" + textBox1.Text + "'";//接受textBox1的字符串
string Delete = "DELETE FROM student WHERE studentName = "+ s;
//delete from 表名 where 字段名='字段值';以上代碼執行后會將所有studentName為textbox中內容的行刪除
OleDbCommand myCommand = new OleDbCommand(Delete, dbconn);//執行命令
myCommand.ExecuteNonQuery();//更新數據庫,返回受影響行數;可通過判斷其是否>0來判斷操作是否成功
修改操作:利用update方法,在dbconn.Open();后添加以下代碼,然后將所有代碼復制到對應按鈕的click事件下
string s = "'" + textBox1.Text + "'", x = "'" + textBox2.Text + "'"; 接受textBox的字符串
string Update = "UPDATE student SET studentName=" + x + "WHERE studentName = " + s;
//update 表名 set 字段名='字段值' where 字段值='字段值';上一行代碼執行后將所有studentName中的s替換為x
OleDbCommand myCommand = new OleDbCommand(Update, dbconn);//執行命令
myCommand.ExecuteNonQuery();//更新數據庫,返回受影響行數;可通過判斷其是否>0來判斷操作是否成功
查詢操作:利用select方法,在dbconn.Open();后添加以下代碼,修改OleDbDataAdapter inst為第三行內容,然后將所有代碼復制到對應按鈕的click事件下
string s = "'" + textBox1.Text + "'";//接受textBox1的字符串
string Select = "SELECT *FROM student WHERE studentName = " + s;
//select *from 表名 where 字段名='字段值';*表示全表,從全表中
OleDbDataAdapter inst = new OleDbDataAdapter(Select, dbconn);//只匹配滿足條件的行
注意增刪改查的代碼均插入到打開數據庫代碼:
dbconn.Open();//打開連接操作
之后;
查詢后:
MessageBox.Show(ds.Tables[0].Rows[0]["studentNO"].ToString());
------
不要看他人高薪,且看閑時誰在拼
---------------
作者:來晚了的沒有名字
來源:CSDN
原文:https://blog.csdn.net/qq_36382357/article/details/80466326
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
