一、連接VS2013自帶的本地數據庫
using System.Data.SqlClient;
首先定義一個連接字符串
public static string ConnectString = "Server=(localdb)\\Projects;Initial Catalog=Test;Integrated Security=true";
其中:Server是服務器名
Ilitial Catalog是數據庫名
Integrated Security是集成驗證,使用Windows驗證的方式去連接到數據庫服務器。不需要在連接字符串中編寫用戶名和密碼,從一定程度上說提高了安全性。(該參數為false時或省略該項時,按照Userid和password來連接,設為SSPI時相當於true。)
using (SqlConnection conn = new SqlConnection(ConnectString)) { string sql = "select password,level from [Test].[dbo].[User] where userid='" + username + "'"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { if(sdr.Read()) { //則將對應該用戶名下的 第一個字段 即使密碼(select的第一個字段) 賦給 字符串pwd,並且依次往后讀取 所有的密碼 //Trim()方法為移除字符串前后的空白 string pwd = sdr.GetString(0).Trim(); //讀取器sdr獲取了2列數據 第1列為密碼索引為0 第2列即索引為1的是用戶類型 string uType = sdr.GetString(1).Trim(); if (pwd == password) { //獲取登陸成功后的用戶ID Uid = username; UserType = uType; if(UserType=="普通用戶") { this.Hide(); User muser = new User(); muser.ShowDialog(); } else if(UserType== "高級用戶") { this.Hide(); VipUser mvuser = new VipUser(); mvuser.ShowDialog(); } else if(UserType=="管理員") { this.Hide(); Admimistor madministor = new Admimistor(); madministor.ShowDialog(); } }
SqlConnection:數據庫連接類
SqlCommand:數據庫操作類
SqlDataReader:讀取
二、對數據庫中的數據進行增、刪、查、改(在DataGridview中)
SqlDataAdapter adp = null; DataSet ds = null; private void Admimistor_Load(object sender, EventArgs e) { adp = new SqlDataAdapter("select * from [Test].[dbo].[User]", Login.ConnectString);//實例化橋接器 ds = new DataSet();//實例化數據集 adp.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } //向表中編輯或添加數據 private void button1_Click(object sender, EventArgs e) { SqlCommandBuilder scb = new SqlCommandBuilder(adp); //更新數據 try { //這里是關鍵 adp.Update(ds); } catch (SqlException ex) { MessageBox.Show(ex.Message); } } //刪除表中的選中行 private void button3_Click(object sender, EventArgs e) { foreach (DataGridViewRow dr in dataGridView1.SelectedRows) { MessageBox.Show("確認刪除嗎?"); dataGridView1.Rows.Remove(dr);//刪除一條記錄 } }
SqlDataAdapter是 DataSet和 SQL Server之間的橋接器,用於檢索和保存數據。SqlDataAdapter通過對數據源使用適當的Transact-SQL語句映射 Fill(它可更改DataSet中的數據以匹配數據源中的數據)和 Update(它可更改數據源中的數據以匹配 DataSet中的數據)來提供這一橋接。當SqlDataAdapter填充 DataSet時,它為返回的數據創建必需的表和列(如果這些表和列尚不存在)。
DataSet當成內存中的數據庫,DataSet是不依賴於數據庫的獨立數據集合。所謂獨立,就是說,即使斷開數據鏈路,或者關閉數據庫,DataSet依然是可用的,DataSet在內部是用XML來描述數據的,由於XML是一種與平台無關、與語言無關的數據描述語言,而且可以描述復雜關系的數據,比如父子關系的數據,所以DataSet實際上可以容納具有復雜關系的數據,而且不再依賴於數據庫鏈路。
部分引用自:
1.C#中SqlDataAdapter的使用小結 - CSDN博客
http://blog.csdn.net/nicholaseenzhu/article/details/70417407
2.360百科
