visual studio2019連接SQL Server數據庫,增刪改查詳細教程(C#代碼)

工具:

1.Visual Studio 2019

2.SQL Server數據庫(我使用的2008)

操作:

1.打開SQL Server,打開後會看到數據庫的初始鏈接界面。(如下圖)

 

2..複製上圖中的“服務器名稱”,然後點擊“連接”,進入數據庫。

3.打開vs,創建好自己要用的項目,我寫的項目名稱叫做:‘finnal_test’,要做的是數據庫綜合實習關於獎學金評定的管理系統

4.工具->連接到數據庫->在服務器名裏面,粘貼複製的服務器名

5.在下面選擇自己要連接的數據庫名稱(也可以手動輸入,我連接的是我自己創建的數據庫:shaohui),確定

 

 6.打開“服務器資源管理器”,會看到有下圖信息,點擊“表”可以看到數據庫裏面創建的數據表

 

 

 

連接代碼:

完成上述操作後只是把數據庫添加到了vs裏,要想在項目裏對數據庫進行編輯,還需要寫一些代碼。

1.打開自己的項目,選擇項目->添加類

 

 

 類名自己起,我這裏是SQLServerDataBase

2.打開類文件,寫入以下代碼。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data; using System.Data.SqlClient; using System.Threading.Tasks;//必要的命名空間 namespace finnal_test { class SQLServerDataBase { //MySqlCon部分,每個人不相同,後面我會進行說明,下面的是我計算機相應的配置 private string MySqlCon = "Data Source=DESKTOP-8LDERGD\\SQLEXPRESS;Initial Catalog = shaohui; Integrated Security = True"; public DataTable ExecuteQuery(string sqlStr)//用於查詢;其實是相當於提供一個可以傳參的函數,到時候寫一個sql語句,存在string裏,傳給這個函數,就會自動執行。     { SqlConnection con = new SqlConnection(MySqlCon); con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = sqlStr; DataTable dt = new DataTable(); SqlDataAdapter msda = new SqlDataAdapter(cmd); msda.Fill(dt); con.Close(); return dt; } public int ExecuteUpdate(string sqlStr)//用於增刪改;         { SqlConnection con = new SqlConnection(@MySqlCon); con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.CommandText = sqlStr; int iud = 0; iud = cmd.ExecuteNonQuery(); con.Close(); return iud; } } } 

3.修改代碼裏的MySqlCon,這一步用來連接到數據庫,至關重要。

在“服務器資源管理”處選中數據庫,然後可以在“屬性”窗口找到“連接字符串”,複製其內容,賦給MySqlCon。比如我修改後是:

MySqlCon = "Data Source=DESKTOP-8LDERGD\\SQLEXPRESS;Initial Catalog = shaohui; Integrated Security = True";

                      

完成這些操作後,就可以在form裏寫代碼來修改數據庫了。

增刪改查:

增刪改查的實現都是sql語句,把寫好的sql語句賦給字符串,然後執行。這裏需要注意的是,增刪改是用上面的ExecuteUpdate()函數,而查詢是用的ExecuteQuery()函數。接下來以我的代碼進行舉例:
1.查詢,不顯示查詢結果(數據表名稱爲DBuser)

//查詢操作,驗證身份
            string my_user = username.Text;//賬號
            string my_pass = password.Text;//密碼
            string my_id = authority.Text;//身份
       SQLServerDataBase SQLConn = new SQLServerDataBase(); DataTable d1 = new DataTable(); string sql = "select * from DBuser where username = '"+ my_user + "' and password = '"+ my_pass + "' and id = '"+my_id+"'"; d1 = SQLConn.ExecuteQuery(sql); if(d1!=null&&d1.Rows.Count>0) { this.Hide(); if(my_id=="教師") { HomeForm homeForm = new HomeForm(); homeForm.Show(); } else if(my_id == "管理員") { Administrator administrator = new Administrator(); administrator.Show(); } else if(my_id == "學生") { Student student = new Student(my_user); student.Show(); } } else { MessageBox.Show("賬號或密碼錯誤!!"); username.Text = ""; password.Text = ""; }

2.查詢,顯示查詢結果,我這裏是將查詢到的結果放在了datagridview控件中

private void match2DB(string my_sql)
        {
        SQLServerDataBase SQLConn = new SQLServerDataBase(); dataGridView_match.Rows.Clear();//清空datagridview中數據 int rank = 1;//記錄排名 DataTable d1 = new DataTable(); string sql = my_sql; d1 = SQLConn.ExecuteQuery(sql); if (d1 != null && d1.Rows.Count > 0) { for (int n = 0; n < d1.Rows.Count; n++) { dataGridView_match.Rows.Add(1); dataGridView_match.Rows[n].Cells["num"].Value = rank.ToString(); dataGridView_match.Rows[n].Cells["class2"].Value = d1.Rows[n]["class"]; dataGridView_match.Rows[n].Cells["no2"].Value = d1.Rows[n]["no"]; dataGridView_match.Rows[n].Cells["name2"].Value = d1.Rows[n]["name"]; dataGridView_match.Rows[n].Cells["match_name2"].Value = d1.Rows[n]["match_name"]; dataGridView_match.Rows[n].Cells["match_grade2"].Value = d1.Rows[n]["match_grade"]; rank++; } //偶數行顏色設置 for (int i = 0; i < dataGridView_match.RowCount; i++) { if (i % 2 == 1) dataGridView_match.Rows[i].DefaultCellStyle.BackColor = Color.Silver; } } }

3.除了查詢操作之外,增加,修改,刪除都是使用ExecuteUpdate函數,使用方法類似,下面只用增加作爲例子

SQLServerDataBase SQLConn = new SQLServerDataBase();
string sql = "insert into DBuser values('" + username + "','" + password + "','" + id + "')";
                int result = SQLConn.ExecuteUpdate(sql);//執行後會有返回值,是int類型,如果執行失敗會返回0;
                if (result != 0)
                {
                    MessageBox.Show("添加成功", "添加結果", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else { MessageBox.Show("添加失敗!請重新添加!", "添加結果", MessageBoxButtons.OK, MessageBoxIcon.Information); }

4.代碼中SQLServerDataBase SQLConn = new SQLServerDataBase();主要就是創建了一個連接數據庫類的對象,由於對數據庫操作時多次重複使用,所以建議可以在每一個窗口定義爲全局變量

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章