C# 读取新增修改删除 数据库资料方法.docx

上传人:b****3 文档编号:27264739 上传时间:2023-06-28 格式:DOCX 页数:15 大小:19.05KB
下载 相关 举报
C# 读取新增修改删除 数据库资料方法.docx_第1页
第1页 / 共15页
C# 读取新增修改删除 数据库资料方法.docx_第2页
第2页 / 共15页
C# 读取新增修改删除 数据库资料方法.docx_第3页
第3页 / 共15页
C# 读取新增修改删除 数据库资料方法.docx_第4页
第4页 / 共15页
C# 读取新增修改删除 数据库资料方法.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

C# 读取新增修改删除 数据库资料方法.docx

《C# 读取新增修改删除 数据库资料方法.docx》由会员分享,可在线阅读,更多相关《C# 读取新增修改删除 数据库资料方法.docx(15页珍藏版)》请在冰豆网上搜索。

C# 读取新增修改删除 数据库资料方法.docx

C#读取新增修改删除数据库资料方法

///

///讀取SQLServer數據,使用DataSet

///

privatevoidDataSerConnection()

{

try

{

//1、

/*

*使用SqlConnection?

接?

据?

之前,首先需要建立?

据?

?

接。

*?

了建立?

据?

?

接,需要?

建SqlConnection?

例,并通?

SqlConnection?

构造器或SqlConnection?

例的?

性初始化?

据?

?

接字符串。

*SqlConnection與SqlDataAdapter或SqlCommand一起使用

*/

//SqlConnection表示與SQLServer?

据?

的一?

打?

的?

接。

作用:

控制到SQLServer的連接

//(如果有可用的開啟連接,則SqlConnection會從連接集區取出開啟的連接。

否則,它會建立與SQLServer之執行個體的新連接。

SqlConnectiondataConnection=newSqlConnection();

//ConnectionString取得或設定用來開啟SQLServer資料庫的字串。

dataConnection.ConnectionString="DataSource=CCM02\\SQLEXPRESS;InitialCatalog=Northwind;PersistSecurityInfo=True;UserID=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、

SqlDataAdaptersuppliersTableAdapter=newSqlDataAdapter("select*fromproducts",dataConnection);

/*

*成員名稱說明

DataReader從基礎資料儲存區中擷取資料做為IDataReader

DataSet從基礎資料儲存區中擷取資料至DataSet結構中。

*/

//3、

DataSetdt=newDataSet();

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、

BindingSourcebd=newBindingSource(dt,"products");

//在界面上顯示資料

//dgvData:

DataGridView控件

//取得或設定DataGridView顯示資料的資料來源。

dgvData.DataSource=bd;

//6、

dataConnection.Close();

//釋放所使用的所有資源。

suppliersTableAdapter.Dispose();

}

catch(Exceptione)

{

throwe;

}

}

///

///用DataReader讀取數據

///

privatevoidCommandConnection()

{

try

{

SqlConnectionsqlConn=newSqlConnection();

sqlConn.ConnectionString="DataSource=CCM02\\SQLEXPRESS;InitialCatalog=Northwind;PersistSecurityInfo=True;UserID=sa;Password=sh2_123";

sqlConn.Open();

SqlCommandsqlComad=newSqlCommand();

sqlComad.CommandType=CommandType.Text;

sqlComad.Connection=sqlConn;

sqlComad.CommandText="select*fromproducts";

//SqlDataReader:

從數據庫獲取行

SqlDataReadersqlDr=sqlComad.ExecuteReader();

//FieldCount取得目前資料列中的資料行數目。

DataTabledt=newDataTable();

intiDrCount=sqlDr.FieldCount;

for(intiCnt=0;iCnt

{

stringa=sqlDr.GetName(iCnt);

dt.Columns.Add(a);

//dt.Rows.Add((DataRow)sqlDr[iCnt]);

}

//將DataReader前進到下一個資料

while(sqlDr.Read())

{

//定義一個數組,便於讀出每一行資料

String[]subitems=newString[iDrCount];

//用循環讀出每一行資料

for(intiCnt=0;iCnt

{

//讀出每一行資料保存到數組中

subitems[iCnt]=sqlDr[iCnt].ToString();

stringsValue=sqlDr[iCnt].ToString();

}

//將讀出的行資料增表的行中

dt.Rows.Add(subitems);

}

//DataGridView的來源為“dt”這個表

dgvData.DataSource=dt;

sqlDr.Close();

sqlComad.Dispose();

sqlConn.Close();

}

catch(Exceptione)

{

throwe;

}

}

///

///用表進行填充DataGridView

///

privatevoidDataTableCommandConnect()

{

DataTabledtb=newDataTable();

SqlConnectionsqlConn=newSqlConnection();

sqlConn.ConnectionString="DataSource=CCM02\\SQLEXPRESS;InitialCatalog=Northwind;PersistSecurityInfo=True;UserID=sa;Password=sh2_123";

sqlConn.Open();

SqlCommandsqlCmd=newSqlCommand();

sqlCmd.CommandType=CommandType.Text;

sqlCmd.CommandText="select*fromproducts";

sqlCmd.Connection=sqlConn;

SqlDataAdaptersqlDapter=newSqlDataAdapter();

sqlDapter.SelectCommand=sqlCmd;

dtb.Clear();

//將讀出的資料填充一表dtb中

sqlDapter.Fill(dtb);

//DataGridView的來源為“dt”這個表

dgvData.DataSource=dtb;

sqlConn.Close();

sqlCmd.Dispose();

sqlDapter.Dispose();

}

///

///保存已修改的資料

///

///

///

privatevoidbtnSave_Click(objectsender,EventArgse)

{

DataSetdsChanges=(DataSet)dtSet.GetChanges();

if(dsChanges==null)

{

return;

}

DataTabledtb=newDataTable();

dtb=dsChanges.Tables["products"];

//GetErrors方法返回一個數組,它由表中具一個或多個檢驗錯誤的行構成。

如沒有誤返加空數組

DataRow[]badRows=dtb.GetErrors();

if(badRows.Length==0)

{

//intnumRows=suppliersTableAdapter.Update(dsChanges,"products");

//要在需要?

生成所需的命令,必?

?

建SqlCommandBuilder?

象的?

例并使用?

构造函?

中的DataAdapter。

//1、

SqlCommandBuildersqlbuiler=newSqlCommandBuilder();

sqlbuiler.DataAdapter=suppliersTableAdapter;

//2、

SqlConnectiondataConnection=newSqlConnection();

dataConnection.ConnectionString="DataSource=CCM02\\SQLEXPRESS;InitialCatalog=Northwind;PersistSecurityInfo=True;UserID=sa;Password=sh2_123";

//dataConnection.Open();

stringsCmdText="select*fromproducts";

//3、

SqlCommandsqlComad=newSqlCommand();

//指出CommandText讀取方式

sqlComad.CommandType=CommandType.Text;

//Connection:

連接資料庫的Connection

sqlComad.Connection=dataConnection;

//CommandText:

取得或設定要針對資料來源執行的文字命令。

sqlComad.CommandText=sCmdText;

//4、

//suppliersTableAdapter.SelectCommand=newSqlCommand("select*fromproducts",dataConnection);

//SelectCommand取得或設定用來在資料來源中選取資料錄的命令。

suppliersTableAdapter.SelectCommand=sqlComad;

//取得或設定接資料庫的Connection

//取得或設定用來將新的資料錄插入至資料來源的命令。

//GetInsertCommand:

取得在資料來源上執行插入時所需之自動產生的DbCommand物件。

suppliersTableAdapter.InsertCommand=sqlbuiler.GetInsertCommand();

suppliersTableAdapter.UpdateCommand=sqlbuiler.GetUpdateCommand();

suppliersTableAdapter.DeleteCommand=sqlbuiler.GetDeleteCommand();

//5、

intnumRows=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

{

stringerrorMsg=null;

foreach(DataRowrowinbadRows)

{

//每一行都可能一個或多個誤,而GetColumnsInError方法將返加一個集合,其中包含了數據有問題的所有例

foreach(DataColumncolinrow.GetColumnsInError())

{

//GetColumnError方法獲取一個無效的列的錯誤消息。

每一條錯誤消息都附加到errorMsg字符串上。

errorMsg+=row.GetColumnError(col)+"\n";

}

}

MessageBox.Show("Errorsindata:

"+errorMsg,"pleasefix",MessageBoxButtons.OK,MessageBoxIcon.Error);

}

}

}

///

///新增按鈕,新增一個空行

///

///

///

privatevoidbtnAdd_Click(objectsender,EventArgse)

{

if(dgvData.DataSource!

=null)

{

bd.AddNew();

}

}

///

///刪除按鈕,刪當前資料

///

///

///

privatevoidbtnDelete_Click(objectsender,EventArgse)

{

intiSelectRowCount=dgvData.SelectedRows.Count;

intiSelectCellCount=dgvData.SelectedCells.Count;

intiOldCellIndex=0;

if(iSelectCellCount>0)

{

//判斷是否是選擇了行

if(iSelectRowCount>0)

{

//循環刪除行

foreach(DataGridViewRowdgvRowindgvData.SelectedRows)

{

dgvData.Rows.Remove(dgvRow);

}

MessageBox.Show("Delete"+iSelectRowCount+"rows","Success");

}

//判斷是否是擇了存儲格

if(dgvData.SelectedCells.Count>0)

{

//定義一個ArrayList存放行資料

ArrayListal=newArrayList();

//循環存儲格,得到行Index存入ArrayList

foreach(DataGridViewCelldgvCellindgvData.SelectedCells)

{

/*IndexOf:

搜尋指定的Object,並傳回在整個ArrayList中第一個符合元素之以零起始的索引。

如果有找到,則是在整個ArrayList內,value第一次出現的以零起始的索引,否則為-1。

*/

if(al.IndexOf(dgvCell.RowIndex)==-1)

{

//將行號增加到數組中

al.Add(dgvCell.RowIndex);

}

}

foreach(intiIndexinal)

{

dgvData.Rows.RemoveAt(iIndex);

}

}

}

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

//intiSelectRowCount=dgvData.SelectedRows.Count;

//if(dgvData.SelectedRows.Count>0)

//{

//foreach(DataGridViewRowdgvRowindgvData.SelectedRows)

//{

//dgvData.Rows.Remove(dgvRow);

//}

//MessageBox.Show("Delete"+iSelectRowCount+"rows","Success");

//}

#endregion

#region當選擇存儲格時,刪除該存儲的行

//當選擇的存儲格大於0時(即選擇了多行)

//if(dgvData.SelectedCells.Count>0)

//{

//intiSelectCellsCount=dgvData.SelectedCells.Count;

////刪除方法1

//foreach(DataGridViewCelldgvCellindgvData.SelectedCells)

//{

//intiRowIndex=dgvCell.RowIndex;

//dgvData.Rows.RemoveAt(iRowIndex);

//}

//刪除方法2

//循環刪除時的方法,(要先刪除前一筆,在刪除下一筆,要不然會出錯)

//for(intiCellsCount=iSelectRowCount-1;iCellsCount>=0;iCellsCount--)

//{

//intiRowIndex=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();

}

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 高等教育 > 医学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1