1. 程式人生 > 實用技巧 >visual studio2019連線SQL Server資料庫,增刪改查詳細教程(C#程式碼)

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();主要就是建立了一個連線資料庫類的物件,由於對資料庫操作時多次重複使用,所以建議可以在每一個視窗定義為全域性變數