使用C#與SQL Server數(shù)據庫進行交互的詳細步驟
一.創(chuàng)建數(shù)據庫
用VS 創(chuàng)建數(shù)據庫的步驟:
1.打開vs,創(chuàng)建一個新項目,分別在搜素框中選擇C#、Windows、桌面,然后選擇Windows窗體應用(.NET Framework)
2.打開“視圖-服務器資源管理器”,右鍵單擊“數(shù)據連接”,如圖。在彈出的菜單中選擇【創(chuàng)建新SQL Server 數(shù)據庫】選項,彈出“創(chuàng)建新的SQL Server數(shù)據庫”對話框。
3.對應項目,系統(tǒng)添加數(shù)據庫連接。(要是電腦沒有sql server,可以選中“視圖-sql server資源管理器”創(chuàng)建數(shù)據庫)
連接成功即如下(第一次可能只有一個)
4.新建數(shù)據庫XSCJDB(學生成績數(shù)據庫),點開第二個小三角-右鍵點擊數(shù)據庫-添加新數(shù)據庫
自己取名(最好采用英文命名)
5.選中該數(shù)據庫并創(chuàng)建新表student,點擊新建數(shù)據庫前的小三角-右鍵表-添加新表
6.表中插入屬性,雙擊即可打開
7.右鍵選中表查看表中數(shù)據
二.使用控件實現(xiàn)連接數(shù)據庫并對其操作
(1)在工具箱中拖出dataGridView控件和botton控件(可以改名使其功能明確)
(2)雙擊botton1,進入代碼編寫(檢查數(shù)據庫的連接)
private void button1_Click(object sender, EventArgs e) { string strcom = @"Data Source = (localdb)\ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;"; SqlConnection sqlcon; using (sqlcon = new SqlConnection(strcom)) { sqlcon.Open(); MessageBox.Show("數(shù)據庫連接狀態(tài)" + sqlcon.State.ToString(), "第一個對話框"); } MessageBox.Show("數(shù)據庫連接狀態(tài)" + sqlcon.State.ToString(), "第二個對話框"); }
注意:
此處應根據自己的電腦修改,具體步驟如下:
單擊剛建的數(shù)據庫-在右下角解決方案資源管理器中找到連接字符串-復制第一個True前面的內容
(3)雙擊雙擊botton2,進入代碼編寫(插入數(shù)據)
private void button2_Click(object sender, EventArgs e) { string strcom = @"Data Source = (localdb)\ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;"; SqlConnection conn =null; try { conn = new SqlConnection(strcom); conn.Open(); SqlCommand mycmm= new SqlCommand(); mycmm.Connection = conn; mycmm.CommandType = CommandType.Text; mycmm.CommandText = @"insert into student(Id,name,major,grade,tel) values(@Id,@name,@major,@grade,@tel)"; mycmm.Parameters.Add(new SqlParameter("@Id", 2022002)); mycmm.Parameters.Add(new SqlParameter("@name", "李四")); mycmm.Parameters.Add(new SqlParameter("@major", "CS")); mycmm.Parameters.Add(new SqlParameter("@grade","80")); mycmm.Parameters.Add(new SqlParameter("@tel","13999216")); int returnvalue=mycmm.ExecuteNonQuery(); if(returnvalue!=-1) { MessageBox.Show("數(shù)據插入成功"); } } catch(Exception ex) { if(conn != null) { MessageBox.Show("數(shù)據插入失敗" + ex.Message); } } }
(4)雙擊雙擊botton3,進入代碼編寫(查詢全部數(shù)據)
// 處理button3的點擊事件,從數(shù)據庫中查詢并顯示所有數(shù)據 private void button3_Click(object sender, EventArgs e) { // 數(shù)據庫連接字符串 string strcom = @"Data Source = (localdb)\ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;"; SqlConnection conn = null; try { // 初始化并打開數(shù)據庫連接 conn = new SqlConnection(strcom); conn.Open(); // 創(chuàng)建并配置SqlCommand對象 SqlCommand mycmm = new SqlCommand { Connection = conn, CommandType = CommandType.Text, CommandText = @"select * from student" }; // 使用SqlDataAdapter填充DataSet SqlDataAdapter sda = new SqlDataAdapter(mycmm); DataSet ds = new DataSet(); sda.Fill(ds, "studentList"); // 顯示查詢結果到DataGridView dataGridView2.DataSource = ds.Tables["studentList"].DefaultView; // 關閉數(shù)據庫連接 conn.Close(); } catch (Exception ex) { // 處理異常 MessageBox.Show(ex.Message); if (conn != null) { conn.Close(); } } }
(5)在設計界面再拖入botton以及一個textbox(用于根據姓名查詢)
(6)編寫botton4代碼(按名字查詢)
// 處理button4的點擊事件,根據名字查詢數(shù)據 private void button4_Click(object sender, EventArgs e) { // 數(shù)據庫連接字符串 string strcon = @"Data Source = (localdb)\ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;"; SqlConnection myConnection = new SqlConnection(strcon); try { // 打開數(shù)據庫連接 myConnection.Open(); // 創(chuàng)建并配置SqlCommand對象 SqlCommand myCommand = new SqlCommand { Connection = myConnection, CommandType = CommandType.Text, CommandText = @"select * from student where name =@name" }; // 添加參數(shù)并賦值 myCommand.Parameters.Add(new SqlParameter("@name", textBox1.Text)); // 執(zhí)行查詢命令并檢查結果 int res = Convert.ToInt32(myCommand.ExecuteScalar()); if (res == 0) { throw new Exception("查無此人"); } // 使用SqlDataAdapter填充DataSet SqlDataAdapter sda = new SqlDataAdapter(myCommand); DataSet ds = new DataSet(); sda.Fill(ds, "xr"); // 顯示查詢結果到DataGridView dataGridView2.DataSource = ds.Tables["xr"].DefaultView; // 關閉數(shù)據庫連接 myConnection.Close(); } catch (Exception ex) { // 處理異常 MessageBox.Show(ex.ToString()); if (myConnection != null) { myConnection.Close(); } } }
(7)對于dataGritView的代碼
// 保存編輯單元格的原始值 object cellTempValue = null; // 單元格開始編輯事件 private void dataGridView2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { // 保存單元格的原始值 cellTempValue = this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; } // 單元格結束編輯事件 private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) { // 如果單元格值沒有改變,返回 if (object.Equals(cellTempValue, this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value)) { return; } // 彈出確認修改對話框 if (MessageBox.Show("是否確定修改,并更新到數(shù)據庫", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) { // 如果取消修改,恢復原值 this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellTempValue; return; } // 數(shù)據庫連接字符串 string strcom = @"your string"; SqlConnection myConnection = new SqlConnection(strcom); try { // 打開數(shù)據庫連接 myConnection.Open(); // 創(chuàng)建并配置SqlCommand對象 SqlCommand myCommand = new SqlCommand { Connection = myConnection, CommandType = CommandType.Text }; // 構建更新SQL語句 string strSql = String.Format( "update student set {0}='{1}' where Id='{2}'", this.dataGridView2.Columns[e.ColumnIndex].HeaderText, // 當前選擇的列名 this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, // 選中單元格修改后的值 this.dataGridView2.Rows[e.RowIndex].Cells[0].Value // 選中單元格修改前的值 ); // 設置命令文本 myCommand.CommandText = strSql; // 執(zhí)行更新命令 int res = myCommand.ExecuteNonQuery(); // 檢查更新是否成功 if (res == 0) { throw new Exception("修改失敗"); } else { MessageBox.Show("修改成功"); } // 關閉數(shù)據庫連接 myConnection.Close(); } catch (Exception ex) { // 處理異常 MessageBox.Show(ex.ToString()); if (myConnection != null) { myConnection.Close(); } } }
三.實現(xiàn)
1.設計界面
2.運行
2.1連接數(shù)據庫(點擊連接數(shù)據庫-確定-確定)即連接成功
2.2增加數(shù)據
2.3查詢全部數(shù)據
2.4按名字查詢
四.小結及易錯點
這個Windows Forms應用程序展示了如何連接本地數(shù)據庫XSCJDB,并實現(xiàn)了數(shù)據插入、查詢和刪除等基本功能。以下是對該應用程序的小結:
1. 數(shù)據庫連接與測試:通過點擊按鈕可以測試與數(shù)據庫的連接,確保應用程序能夠成功連接到本地數(shù)據庫XSCJDB。
2. 數(shù)據插入:點擊相應按鈕可以將預設的學生信息插入到數(shù)據庫的student表中,這提供了一種簡單的數(shù)據錄入方式。
3. 數(shù)據查詢:通過點擊按鈕,應用程序能夠查詢并顯示student表中的所有數(shù)據,使用戶可以輕松地查看數(shù)據庫中存儲的信息。
4. 按姓名查詢:應用程序還提供了按姓名查詢學生數(shù)據的功能,用戶只需輸入學生姓名,即可獲取相應的學生信息。
5. 數(shù)據刪除:用戶可以根據學生姓名刪除相應的學生記錄,這增加了對數(shù)據的管理和維護功能。
在編寫這個應用程序時,需要注意以下易錯點:
- 數(shù)據庫連接字符串的正確性:確保連接字符串中的數(shù)據庫名稱、實例名稱等信息正確無誤,以保證成功連接到數(shù)據庫。
- SQL語句的準確性:編寫SQL語句時,應確保表名和字段名與數(shù)據庫中定義的一致,以避免出現(xiàn)語法錯誤。
- 參數(shù)化查詢的使用:在執(zhí)行SQL操作時,應該使用參數(shù)化查詢來防止SQL注入攻擊,提高數(shù)據安全性。
- 數(shù)據庫連接的管理:在編寫代碼時,應該使用try-finally塊或者using語句來管理數(shù)據庫連接,確保在異常情況下正確關閉連接,以避免資源泄漏。
- 異常處理和錯誤提示:捕獲并處理所有可能的異常,向用戶提供友好的錯誤提示信息,幫助用戶理解問題所在并采取相應的措施。
通過對這些易錯點的注意和處理,可以確保應用程序的穩(wěn)定性、安全性和用戶友好性。同時,還可以考慮進一步優(yōu)化應用程序的功能和性能,提升用戶體驗。
以上就是使用C#與SQL Server數(shù)據庫進行交互的詳細步驟的詳細內容,更多關于C#與SQL Server交互的資料請關注腳本之家其它相關文章!
相關文章
解析C#中用Process類終止進程,執(zhí)行命令的深入分析
本篇文章是對C#中用Process類終止進程,執(zhí)行命令進行了詳細的分析介紹,需要的朋友參考下2013-05-05WinFrom中l(wèi)abel背景透明的實現(xiàn)方法
這篇文章主要介紹了WinFrom中l(wèi)abel背景透明的實現(xiàn)方法,方法簡單實用,是C#程序設計中非常實用的技巧,需要的朋友可以參考下2014-09-09