最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用C#與SQL Server數(shù)據(jù)庫(kù)進(jìn)行交互的詳細(xì)流程

 更新時(shí)間:2025年11月28日 08:48:27   作者:p***3235  
本文詳細(xì)介紹了如何使用Visual Studio創(chuàng)建Windows窗體應(yīng)用程序連接本地SQL Server數(shù)據(jù)庫(kù),并實(shí)現(xiàn)數(shù)據(jù)插入、查詢和刪除等功能,通過步驟說明和代碼示例,展示了如何使用DataGridView控件和按鈕控件與數(shù)據(jù)庫(kù)進(jìn)行交互,文章還總結(jié)了易錯(cuò)點(diǎn),需要的朋友可以參考下

一.創(chuàng)建數(shù)據(jù)庫(kù)

用VS 創(chuàng)建數(shù)據(jù)庫(kù)的步驟:

1.打開vs,創(chuàng)建一個(gè)新項(xiàng)目,分別在搜素框中選擇C#、Windows、桌面,然后選擇Windows窗體應(yīng)用(.NET Framework)

2.打開“視圖-服務(wù)器資源管理器”,右鍵單擊“數(shù)據(jù)連接”,如圖。在彈出的菜單中選擇【創(chuàng)建新SQL Server 數(shù)據(jù)庫(kù)】選項(xiàng),彈出“創(chuàng)建新的SQL Server數(shù)據(jù)庫(kù)”對(duì)話框。

3.對(duì)應(yīng)項(xiàng)目,系統(tǒng)添加數(shù)據(jù)庫(kù)連接。(要是電腦沒有sql server,可以選中“視圖-sql server資源管理器”創(chuàng)建數(shù)據(jù)庫(kù))

連接成功即如下(第一次可能只有一個(gè))

4.新建數(shù)據(jù)庫(kù)XSCJDB(學(xué)生成績(jī)數(shù)據(jù)庫(kù)),點(diǎn)開第二個(gè)小三角-右鍵點(diǎn)擊數(shù)據(jù)庫(kù)-添加新數(shù)據(jù)庫(kù)

自己取名(最好采用英文命名)

5.選中該數(shù)據(jù)庫(kù)并創(chuàng)建新表student,點(diǎn)擊新建數(shù)據(jù)庫(kù)前的小三角-右鍵表-添加新表

6.表中插入屬性,雙擊即可打開

7.右鍵選中表查看表中數(shù)據(jù)

二.使用控件實(shí)現(xiàn)連接數(shù)據(jù)庫(kù)并對(duì)其操作

(1)在工具箱中拖出dataGridView控件和botton控件(可以改名使其功能明確)

(2)雙擊botton1,進(jìn)入代碼編寫(檢查數(shù)據(jù)庫(kù)的連接)

 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ù)據(jù)庫(kù)連接狀態(tài)" + sqlcon.State.ToString(), "第一個(gè)對(duì)話框");
     }
     MessageBox.Show("數(shù)據(jù)庫(kù)連接狀態(tài)" + sqlcon.State.ToString(), "第二個(gè)對(duì)話框");

 }

注意:

此處應(yīng)根據(jù)自己的電腦修改,具體步驟如下:

單擊剛建的數(shù)據(jù)庫(kù)-在右下角解決方案資源管理器中找到連接字符串-復(fù)制第一個(gè)True前面的內(nèi)容

(3)雙擊雙擊botton2,進(jìn)入代碼編寫(插入數(shù)據(jù))

  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ù)據(jù)插入成功");
          }
      }
      catch(Exception ex) 
      {
          if(conn != null)
          {
              MessageBox.Show("數(shù)據(jù)插入失敗" + ex.Message);
          }
      }
  }

(4)雙擊雙擊botton3,進(jìn)入代碼編寫(查詢?nèi)繑?shù)據(jù))

 // 處理button3的點(diǎn)擊事件,從數(shù)據(jù)庫(kù)中查詢并顯示所有數(shù)據(jù)
 private void button3_Click(object sender, EventArgs e)
 {
     // 數(shù)據(jù)庫(kù)連接字符串
     string strcom = @"Data Source = (localdb)ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;";
     SqlConnection conn = null;

     try
     {
         // 初始化并打開數(shù)據(jù)庫(kù)連接
         conn = new SqlConnection(strcom);
         conn.Open();

         // 創(chuàng)建并配置SqlCommand對(duì)象
         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");

         // 顯示查詢結(jié)果到DataGridView
         dataGridView2.DataSource = ds.Tables["studentList"].DefaultView;

         // 關(guān)閉數(shù)據(jù)庫(kù)連接
         conn.Close();
     }
     catch (Exception ex)
     {
         // 處理異常
         MessageBox.Show(ex.Message);
         if (conn != null)
         {
             conn.Close();
         }
     }
 }

(5)在設(shè)計(jì)界面再拖入botton以及一個(gè)textbox(用于根據(jù)姓名查詢)

(6)編寫botton4代碼(按名字查詢)

       // 處理button4的點(diǎn)擊事件,根據(jù)名字查詢數(shù)據(jù)
       private void button4_Click(object sender, EventArgs e)
       {
           // 數(shù)據(jù)庫(kù)連接字符串
           string strcon = @"Data Source = (localdb)ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;";
           SqlConnection myConnection = new SqlConnection(strcon);

           try
           {
               // 打開數(shù)據(jù)庫(kù)連接
               myConnection.Open();

               // 創(chuàng)建并配置SqlCommand對(duì)象
               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í)行查詢命令并檢查結(jié)果
               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");

               // 顯示查詢結(jié)果到DataGridView
               dataGridView2.DataSource = ds.Tables["xr"].DefaultView;

               // 關(guān)閉數(shù)據(jù)庫(kù)連接
               myConnection.Close();
           }
           catch (Exception ex)
           {
               // 處理異常
               MessageBox.Show(ex.ToString());
               if (myConnection != null)
               {
                   myConnection.Close();
               }
           }
       }

(7)對(duì)于dataGritView的代碼

// 保存編輯單元格的原始值
object cellTempValue = null;
 
// 單元格開始編輯事件
private void dataGridView2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    // 保存單元格的原始值
    cellTempValue = this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
}
 
// 單元格結(jié)束編輯事件
private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    // 如果單元格值沒有改變,返回
    if (object.Equals(cellTempValue, this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
    {
        return;
    }
 
    // 彈出確認(rèn)修改對(duì)話框
    if (MessageBox.Show("是否確定修改,并更新到數(shù)據(jù)庫(kù)", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
    {
        // 如果取消修改,恢復(fù)原值
        this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellTempValue;
        return;
    }
 
    // 數(shù)據(jù)庫(kù)連接字符串
    string strcom = @"your string";
    SqlConnection myConnection = new SqlConnection(strcom);
 
    try
    {
        // 打開數(shù)據(jù)庫(kù)連接
        myConnection.Open();
 
        // 創(chuàng)建并配置SqlCommand對(duì)象
        SqlCommand myCommand = new SqlCommand
        {
            Connection = myConnection,
            CommandType = CommandType.Text
        };
 
        // 構(gòu)建更新SQL語句
        string strSql = String.Format(
            "update student set {0}='{1}' where Id='{2}'",
            this.dataGridView2.Columns[e.ColumnIndex].HeaderText, // 當(dāng)前選擇的列名
            this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value, // 選中單元格修改后的值
            this.dataGridView2.Rows[e.RowIndex].Cells[0].Value // 選中單元格修改前的值
        );
 
        // 設(shè)置命令文本
        myCommand.CommandText = strSql;
 
        // 執(zhí)行更新命令
        int res = myCommand.ExecuteNonQuery();
 
        // 檢查更新是否成功
        if (res == 0)
        {
            throw new Exception("修改失敗");
        }
        else
        {
            MessageBox.Show("修改成功");
        }
 
        // 關(guān)閉數(shù)據(jù)庫(kù)連接
        myConnection.Close();
    }
    catch (Exception ex)
    {
        // 處理異常
        MessageBox.Show(ex.ToString());
        if (myConnection != null)
        {
            myConnection.Close();
        }
    }
}

三.實(shí)現(xiàn)

1.設(shè)計(jì)界面

2.運(yùn)行

2.1連接數(shù)據(jù)庫(kù)(點(diǎn)擊連接數(shù)據(jù)庫(kù)-確定-確定)即連接成功

2.2增加數(shù)據(jù)

2.3查詢?nèi)繑?shù)據(jù)

2.4按名字查詢

四.小結(jié)及易錯(cuò)點(diǎn)

這個(gè)Windows Forms應(yīng)用程序展示了如何連接本地?cái)?shù)據(jù)庫(kù)XSCJDB,并實(shí)現(xiàn)了數(shù)據(jù)插入、查詢和刪除等基本功能。以下是對(duì)該應(yīng)用程序的小結(jié):

1. 數(shù)據(jù)庫(kù)連接與測(cè)試:通過點(diǎn)擊按鈕可以測(cè)試與數(shù)據(jù)庫(kù)的連接,確保應(yīng)用程序能夠成功連接到本地?cái)?shù)據(jù)庫(kù)XSCJDB。

2. 數(shù)據(jù)插入:點(diǎn)擊相應(yīng)按鈕可以將預(yù)設(shè)的學(xué)生信息插入到數(shù)據(jù)庫(kù)的student表中,這提供了一種簡(jiǎn)單的數(shù)據(jù)錄入方式。

3. 數(shù)據(jù)查詢:通過點(diǎn)擊按鈕,應(yīng)用程序能夠查詢并顯示student表中的所有數(shù)據(jù),使用戶可以輕松地查看數(shù)據(jù)庫(kù)中存儲(chǔ)的信息。

4. 按姓名查詢:應(yīng)用程序還提供了按姓名查詢學(xué)生數(shù)據(jù)的功能,用戶只需輸入學(xué)生姓名,即可獲取相應(yīng)的學(xué)生信息。

5. 數(shù)據(jù)刪除:用戶可以根據(jù)學(xué)生姓名刪除相應(yīng)的學(xué)生記錄,這增加了對(duì)數(shù)據(jù)的管理和維護(hù)功能。

在編寫這個(gè)應(yīng)用程序時(shí),需要注意以下易錯(cuò)點(diǎn):

  • 數(shù)據(jù)庫(kù)連接字符串的正確性:確保連接字符串中的數(shù)據(jù)庫(kù)名稱、實(shí)例名稱等信息正確無誤,以保證成功連接到數(shù)據(jù)庫(kù)。
  • SQL語句的準(zhǔn)確性:編寫SQL語句時(shí),應(yīng)確保表名和字段名與數(shù)據(jù)庫(kù)中定義的一致,以避免出現(xiàn)語法錯(cuò)誤。
  • 參數(shù)化查詢的使用:在執(zhí)行SQL操作時(shí),應(yīng)該使用參數(shù)化查詢來防止SQL注入攻擊,提高數(shù)據(jù)安全性。
  • 數(shù)據(jù)庫(kù)連接的管理:在編寫代碼時(shí),應(yīng)該使用try-finally塊或者using語句來管理數(shù)據(jù)庫(kù)連接,確保在異常情況下正確關(guān)閉連接,以避免資源泄漏。
  • 異常處理和錯(cuò)誤提示:捕獲并處理所有可能的異常,向用戶提供友好的錯(cuò)誤提示信息,幫助用戶理解問題所在并采取相應(yīng)的措施。

通過對(duì)這些易錯(cuò)點(diǎn)的注意和處理,可以確保應(yīng)用程序的穩(wěn)定性、安全性和用戶友好性。同時(shí),還可以考慮進(jìn)一步優(yōu)化應(yīng)用程序的功能和性能,提升用戶體驗(yàn)。

以上就是使用C#與SQL Server數(shù)據(jù)庫(kù)進(jìn)行交互的詳細(xì)流程的詳細(xì)內(nèi)容,更多關(guān)于C#與SQL Server進(jìn)行交互的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

昆山市| 横峰县| 永清县| 朝阳区| 揭东县| 通化县| 永春县| 祁阳县| 胶州市| 尉犁县| 五家渠市| 星座| 偃师市| 上栗县| 邻水| 正定县| 扶风县| 五大连池市| 同心县| 新巴尔虎右旗| 开鲁县| 唐海县| 康乐县| 香河县| 安仁县| 佳木斯市| 辉南县| 玛曲县| 名山县| 大石桥市| 读书| 含山县| 当阳市| 油尖旺区| 柳江县| 勃利县| 石门县| 禹城市| 衡阳县| 濮阳市| 南召县|