C# 讀取、新增、修改、刪除 數據庫資料方法

原文地址为: C# 讀取、新增、修改、刪除 數據庫資料方法

        ///   <summary>
        
///  讀取SQL Server數據,使用DataSet
        
///   </summary>
         private   void  DataSerConnection()
        {
            
try
            {
                
//  1、
        /*
         * 使用SqlConnection连接数据库之前,首先需要建立数据库连接。
         * 为了建立数据库连接,需要创建SqlConnection实例,并通过SqlConnection类构造器或SqlConnection实例的属性初始化数据库连接字符串。
         * SqlConnection 與 SqlDataAdapter 或 SqlCommand一起使用
          */
                 // SqlConnection 表示與SQL Server 数据库的一个打开的连接。作用:控制到SQL Server的連接
                
// (如果有可用的開啟連接,則 SqlConnection 會從連接集區取出開啟的連接。否則,它會建立與 SQL Server 之執行個體的新連接。)
                SqlConnection dataConnection  =   new  SqlConnection();
                
// ConnectionString 取得或設定用來開啟 SQL Server 資料庫的字串。
                dataConnection.ConnectionString  =   " Data Source=CCM02\\SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sh2_123 " ;
                
// Open 開啟資料庫連接。 
                dataConnection.Open();


                
// SqlDataAdapter 表示一組資料命令集和資料庫連接
                 /*
                 * 初始化 SqlDataAdapter 類別的新執行個體
                 * 名稱                            說明
                    SqlDataAdapter ()                                     初始化 SqlDataAdapter 類別的新執行個體。 
                    SqlDataAdapter (SqlCommand)                  使用指定 SqlCommand 做為 SelectCommand 屬性,初始化 SqlDataAdapter 類別的新執行個體。 
                    SqlDataAdapter (String, SqlConnection)      使用 SelectCommand 和 SqlConnection 物件,初始化 SqlDataAdapter 類別的新執行個體。 
                    SqlDataAdapter (String, String)                   使用 SelectCommand 和連接字串,初始化 SqlDataAdapter 類別的新執行個體。 
                 
*/

                 // 2、
                SqlDataAdapter suppliersTableAdapter  =   new  SqlDataAdapter( " select * from products " , dataConnection);

                
/*
                 * 成員名稱 說明 
                    DataReader  從基礎資料儲存區中擷取資料做為 IDataReader  
                    DataSet        從基礎資料儲存區中擷取資料至 DataSet 結構中。
                 
*/

                 // 3、
                DataSet dt  =   new  DataSet();
                dt.DataSetName 
=   " Northwind " ;


                
/*
                 * 名稱                                            說明  
                    DataAdapter.FillSchema (DataSet, SchemaType)                                   將 DataTable 加入至指定的 DataSet,並且根據指定的 SchemaType 設定結構描述,以符合資料來源中的資料表。                      
                    DataAdapter.FillSchema (DataTable, SchemaType, IDataReader)           將 DataTable 加入指定的 DataSet。                      
                    DataAdapter.FillSchema (DataSet, SchemaType, String, IDataReader)    將 DataTable 加入指定的 DataSet。 
                 * 
                 * SchemaType :指定如何在執行 FillSchema 作業時處理現有的結構描述 (Schema) 對應。 
                 * 成員名稱 說明 
                     Mapped       套用所有的現有資料表對應至內送的結構描述 (Schema)。使用變形的結構描述來設定 DataSet。  
                     Source         忽略在 DataAdapter 上的任何資料表對應。使用內送的結構描述來設定 DataSet,而不套用任何的變形。               
                 
*/

                
// 4、
                suppliersTableAdapter.Fill(dt,  " products " );

                
/*
                 * BindingSource
                 * 封裝表單的資料來源。
                 * 名稱                  說明  
                    BindingSource ()                        初始化 BindingSource 類別的新執行個體成為預設屬性值。 
                    BindingSource (IContainer)         初始化 BindingSource 類別的新執行個體,並將 BindingSource 加入指定的容器中。 
                    BindingSource (Object, String)    使用指定的資料來源和資料成員,初始化 BindingSource 類別的新執行個體。 
                 
*/

                 // 5、
                BindingSource bd  =   new  BindingSource(dt,  " products " );

                
// 在界面上顯示資料
                
// dgvData: DataGridView控件
                
// 取得或設定 DataGridView 顯示資料的資料來源。
                dgvData.DataSource  =  bd;

                //6、

                dataConnection.Close();
                
// 釋放所使用的所有資源。
                suppliersTableAdapter.Dispose();

            }
            
catch  (Exception e)
            {
                
throw  e;
            }
        }

         ///   <summary>
        
///  用DataReader讀取數據
        
///   </summary>
         private   void  CommandConnection()
        {
            
try
            {
                SqlConnection sqlConn 
=   new  SqlConnection();
                sqlConn.ConnectionString 
=   " Data Source=CCM02\\SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sh2_123 " ;
                sqlConn.Open();

                SqlCommand sqlComad 
=   new  SqlCommand();
                sqlComad.CommandType 
=  CommandType.Text;
                sqlComad.Connection 
=  sqlConn;
                sqlComad.CommandText 
=   " select * from products " ;

                
// SqlDataReader:從數據庫獲取行
                SqlDataReader sqlDr  =  sqlComad.ExecuteReader();
                
// FieldCount  取得目前資料列中的資料行數目。
                DataTable dt  =   new  DataTable();

                
int  iDrCount  =  sqlDr.FieldCount;
                
for  ( int  iCnt  =   0 ; iCnt  <  iDrCount; iCnt ++ )
                {
                    
string  a  =  sqlDr.GetName(iCnt);
                    dt.Columns.Add(a);
                    
// dt.Rows.Add((DataRow)sqlDr[iCnt]);
                }
                
// 將DataReader前進到下一個資料
                 while  (sqlDr.Read())
                { 
                    
// 定義一個數組,便於讀出每一行資料
                    String[] subitems  =   new  String[iDrCount];
                    
// 用循環讀出每一行資料
                     for  ( int  iCnt  =   0 ; iCnt  <  iDrCount; iCnt ++ )
                    {
                        
// 讀出每一行資料保存到數組中
                        subitems[iCnt]  =  sqlDr[iCnt].ToString();
                        
string  sValue  =  sqlDr[iCnt].ToString();  
                    }
                    
// 將讀出的行資料增表的行中
                    dt.Rows.Add(subitems);
                }
                
// DataGridView的來源為“dt”這個表
                dgvData.DataSource  =  dt;

                sqlDr.Close();
                sqlComad.Dispose();
                sqlConn.Close();
            }
            
catch  (Exception e)
            {
                
throw  e;
            }
        }
 

        ///   <summary>
         ///  用表進行填充DataGridView
        
///   </summary>
         private   void  DataTableCommandConnect()
        {
            DataTable dtb 
=   new  DataTable();

            SqlConnection sqlConn 
=   new  SqlConnection();
            sqlConn.ConnectionString 
=   " Data Source=CCM02\\SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sh2_123 " ;
            sqlConn.Open();

            SqlCommand sqlCmd 
=   new  SqlCommand();
            sqlCmd.CommandType 
=  CommandType.Text;
            sqlCmd.CommandText 
=   " select * from products " ;
            sqlCmd.Connection 
=  sqlConn;

            SqlDataAdapter sqlDapter 
=   new  SqlDataAdapter();
            sqlDapter.SelectCommand 
=  sqlCmd;


            dtb.Clear();
            
// 將讀出的資料填充一表dtb中
            sqlDapter.Fill(dtb);

            
// DataGridView的來源為“dt”這個表
            dgvData.DataSource  =  dtb;

            sqlConn.Close();
            sqlCmd.Dispose();
            sqlDapter.Dispose();
        }

         ///   <summary>
        
///  保存已修改的資料
        
///   </summary>
        
///   <param name="sender"></param>
        
///   <param name="e"></param>
         private   void  btnSave_Click( object  sender, EventArgs e)
        {
            
            DataSet dsChanges 
=  (DataSet)dtSet.GetChanges();
            
if  (dsChanges == null )
            {
                
return ;
            }

            DataTable dtb 
=   new  DataTable();
            dtb 
=  dsChanges.Tables[ " products " ];
            
// GetErrors方法返回一個數組,它由表中具一個或多個檢驗錯誤的行構成。如沒有誤返加空數組
            DataRow[] badRows  =  dtb.GetErrors();

            
if  (badRows.Length == 0 )
            {
                
// int numRows = suppliersTableAdapter.Update(dsChanges, "products");
                
// 要在需要时生成所需的命令,必须创建 SqlCommandBuilder 对象的实例并使用该构造函数中的 DataAdapter。
                //1、

                SqlCommandBuilder sqlbuiler  =   new  SqlCommandBuilder();
                sqlbuiler.DataAdapter 
=  suppliersTableAdapter;

                //2、

                SqlConnection dataConnection  =   new  SqlConnection();
                dataConnection.ConnectionString 
=   " Data Source=CCM02\\SQLEXPRESS;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sh2_123 " ;

                
// dataConnection.Open();

                
string  sCmdText  =   " select * from products " ;
                
//3、
                SqlCommand sqlComad  =   new  SqlCommand();
                
// 指出CommandText讀取方式
                sqlComad.CommandType  =  CommandType.Text;
                
// Connection:連接資料庫的Connection
                sqlComad.Connection  =  dataConnection;
                
// CommandText:取得或設定要針對資料來源執行的文字命令。
                sqlComad.CommandText  =  sCmdText;

                
// 4、
                
// suppliersTableAdapter.SelectCommand = new SqlCommand("select * from products ", dataConnection);
                
// SelectCommand 取得或設定用來在資料來源中選取資料錄的命令。
                suppliersTableAdapter.SelectCommand  =  sqlComad;
                
// 取得或設定接資料庫的Connection
                
// 取得或設定用來將新的資料錄插入至資料來源的命令。 
                
// GetInsertCommand:取得在資料來源上執行插入時所需之自動產生的 DbCommand 物件。
                suppliersTableAdapter.InsertCommand  =  sqlbuiler.GetInsertCommand();
                suppliersTableAdapter.UpdateCommand 
=  sqlbuiler.GetUpdateCommand();
                suppliersTableAdapter.DeleteCommand 
=  sqlbuiler.GetDeleteCommand();


                
//5、
                 int  numRows  =  suppliersTableAdapter.Update(dsChanges,  " products " );

                
if  (numRows > 0 )
                {
                    MessageBox.Show(
" Update "   +  numRows  +   " rows " " Success " );
                    
// 變更資料
                    dtSet.AcceptChanges();
                }
                
else
                {
                    
// 返原所有更
                    dtSet.RejectChanges();
                }

                
// 清除與這個 DbCommandBuilder 關聯的命令。 
                sqlbuiler.RefreshSchema();
                
// 關閉聯接
                dataConnection.Close();
                
// 釋放資源
                sqlComad.Dispose();
                sqlbuiler.Dispose();
            }
            
else
            {
                
string  errorMsg  =   null ;
                
foreach  (DataRow row  in  badRows)
                {
                    
// 每一行都可能一個或多個誤,而GetColumnsInError方法將返加一個集合,其中包含了數據有問題的所有例
                     foreach  (DataColumn col  in  row.GetColumnsInError())
                    {
                        
// GetColumnError方法獲取一個無效的列的錯誤消息。每一條錯誤消息都附加到errorMsg字符串上。
                        errorMsg  +=  row.GetColumnError(col)  +   " \n " ;
                    }
                }
                MessageBox.Show(
" Errors in data: "   +  errorMsg,  " please fix " , MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

         ///   <summary>
        
///  新增按鈕,新增一個空行
        
///   </summary>
        
///   <param name="sender"></param>
        
///   <param name="e"></param>
         private   void  btnAdd_Click( object  sender, EventArgs e)
        {
            
if  (dgvData.DataSource != null )
            {
                bd.AddNew();
            }            
        }

         ///   <summary>
        
///  刪除按鈕,刪當前資料
        
///   </summary>
        
///   <param name="sender"></param>
        
///   <param name="e"></param>
         private   void  btnDelete_Click( object  sender, EventArgs e)
        {
            
int  iSelectRowCount  =  dgvData.SelectedRows.Count;
            
int  iSelectCellCount  =  dgvData.SelectedCells.Count;
            
int  iOldCellIndex  =   0 ;
            
if  (iSelectCellCount > 0 )
            {
                
// 判斷是否是選擇了行
                 if  (iSelectRowCount > 0 )
                {
                    
// 循環刪除行
                      foreach  (DataGridViewRow dgvRow  in  dgvData.SelectedRows)
                     {
                         dgvData.Rows.Remove(dgvRow);
                     }
                     MessageBox.Show(
" Delete "   +  iSelectRowCount  +   " rows " " Success " );
                }

                
//  判斷是否是擇了存儲格
                 if  (dgvData.SelectedCells.Count > 0 )
                {
                    
// 定義一個ArrayList存放行資料
                    ArrayList al  =   new  ArrayList();
                    
// 循環存儲格,得到行Index存入ArrayList
                     foreach  (DataGridViewCell dgvCell  in  dgvData.SelectedCells)
                    {
                        
/* IndexOf:搜尋指定的 Object,並傳回在整個 ArrayList 中第一個符合元素之以零起始的索引。 
                        如果有找到,則是在整個 ArrayList 內,value 第一次出現的以零起始的索引,否則為 -1。 
                         
*/
                        
if  (al.IndexOf(dgvCell.RowIndex)  ==   - 1 )
                        {
                            
// 將行號增加到數組中
                            al.Add(dgvCell.RowIndex);
                        }
                    }
                    
foreach  ( int  iIndex  in  al)
                    {
                        dgvData.Rows.RemoveAt(iIndex);
                    }
                }
            }

            
#region  當選擇行時,刪除該行

            
// int iSelectRowCount = dgvData.SelectedRows.Count;
            
// if (dgvData.SelectedRows.Count > 0)
            
// {
            
//     foreach (DataGridViewRow dgvRow in dgvData.SelectedRows)
            
//     {
            
//         dgvData.Rows.Remove(dgvRow);
            
//     }
            
//     MessageBox.Show("Delete" + iSelectRowCount + "rows", "Success");
            
// }

            
#endregion

            
#region  當選擇存儲格時,刪除該存儲的行
            
// 當選擇的存儲格大於0時(即選擇了多行)
            
// if (dgvData.SelectedCells.Count >0)
            
// {
            
//     int iSelectCellsCount = dgvData.SelectedCells.Count;
            
//      // 刪除方法1
            
//     foreach (DataGridViewCell dgvCell in dgvData.SelectedCells)
            
//     {
            
//         int iRowIndex = dgvCell.RowIndex;
            
//         dgvData.Rows.RemoveAt(iRowIndex);
            
//     }

                
// 刪除方法2
                
// 循環刪除時的方法,(要先刪除前一筆,在刪除下一筆,要不然會出錯)
                
// for (int iCellsCount = iSelectRowCount-1; iCellsCount >=0 ; iCellsCount--)
                
// {
                
//     int iRowIndex = dgvData.SelectedCells[iCellsCount].RowIndex;
                
//      // 取得所選資料行的索引
                
//     dgvData.Rows.RemoveAt(iRowIndex);
                
// }
            
// }
             #endregion


                
// 刪除當前資料行 方法1
                
// dgvData.Rows.Remove(dgvData.CurrentRow);
                
// 刪除當前資料行 方法2
                
// dgvData.Rows.RemoveAt(dgvData.CurrentCell.RowIndex);
                
// 刪除當前資料行 方法3
                
// bd.RemoveCurrent();
        }





转载请注明本文地址: C# 讀取、新增、修改、刪除 數據庫資料方法

猜你喜欢

转载自blog.csdn.net/zhengxiuchen86/article/details/82811777