亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2024年08月11日 16:00:59   作者:"_rainbow_"  
在C#中與數(shù)據(jù)庫進(jìn)行交互,通常使用ADO.NET(ActiveX Data Objects .NET)框架,ADO.NET是.NET Framework中用于數(shù)據(jù)訪問的一組類庫,它提供了多種用于連接和操作數(shù)據(jù)庫的方法,以下是使用C#與SQL Server數(shù)據(jù)庫進(jìn)行交互的詳細(xì)步驟,需要的朋友可以參考下

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

注意:

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

單擊剛建的數(shù)據(jù)庫-在右下角解決方案資源管理器中找到連接字符串-復(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ù)庫中查詢并顯示所有數(shù)據(jù)
 private void button3_Click(object sender, EventArgs e)
 {
     // 數(shù)據(jù)庫連接字符串
     string strcom = @"Data Source = (localdb)\ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;";
     SqlConnection conn = null;
 
     try
     {
         // 初始化并打開數(shù)據(jù)庫連接
         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");
 
         // 顯示查詢結(jié)果到DataGridView
         dataGridView2.DataSource = ds.Tables["studentList"].DefaultView;
 
         // 關(guān)閉數(shù)據(jù)庫連接
         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ù)庫連接字符串
           string strcon = @"Data Source = (localdb)\ProjectModels;Initial Catalog = XSCJDB; Integrated Security = True;";
           SqlConnection myConnection = new SqlConnection(strcon);
 
           try
           {
               // 打開數(shù)據(jù)庫連接
               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í)行查詢命令并檢查結(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ù)庫連接
               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;
}
 
// 單元格結(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)修改對話框
    if (MessageBox.Show("是否確定修改,并更新到數(shù)據(jù)庫", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
    {
        // 如果取消修改,恢復(fù)原值
        this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellTempValue;
        return;
    }
 
    // 數(shù)據(jù)庫連接字符串
    string strcom = @"your string";
    SqlConnection myConnection = new SqlConnection(strcom);
 
    try
    {
        // 打開數(shù)據(jù)庫連接
        myConnection.Open();
 
        // 創(chuàng)建并配置SqlCommand對象
        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ù)庫連接
        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ù)庫(點(diǎn)擊連接數(shù)據(jù)庫-確定-確定)即連接成功

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ù)庫XSCJDB,并實(shí)現(xiàn)了數(shù)據(jù)插入、查詢和刪除等基本功能。以下是對該應(yīng)用程序的小結(jié):

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

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

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

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

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

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

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

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

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

相關(guān)文章

最新評論