SqlCommand对应DateReaderSqlDataAdapter对应DataSetSqlCommand的执行效率比较高,但不灵活,功能也有限SqlDataAdapter的效率要低点,它是连接的,可随时更新数据,功能强大。很多编程用其中一种就可以了。
SqlCommand是C#中与Sql数据库打交道的对象,几乎所有的Sql数据库操作都需要使用该对象来实现,但其功能有限,只是简单的实现了与Sql数据库的接口而已;
//以下使用陈述式写法 听说可以 自动生成 try,finally功能using (SqlConnection connection = new SqlConnection(connectString)){ using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.CommandType = CommandType.Text; command.CommandText = "INSERT into [dbo].[Table_Friber_SN] (Friber_SN, SN, note, OP) VALUES (@Friber_SN, @SN, @note, @OP)"; command.Parameters.AddWithValue("@Friber_SN", LblNewSN.Text); command.Parameters.AddWithValue("@SN", (int)DS.Rows[0][0] + 1); command.Parameters.AddWithValue("@note", "新增SN"); command.Parameters.AddWithValue("@OP", TxtOP.Text); connection.Open(); int recordsAffected = command.ExecuteNonQuery(); LblReturn.Text = recordsAffected.ToString(); LblC9C12.Text = "xxxx"; }}
SqlDataAdapter是一个功能强大的SqL数据适配器,也用于操作Sql数据库,但它的操作都要通过SqlCommand来实现(有一个属性对象的类型就是SqlCommand),也就是说,可以把SqlDataAdapter看作是一个把一些特殊功能封装了、增强了的SqlCommand!adapter是和dataset打交道的,command不能直接与dataset打交道,要通过adapter.adapter的定义是基于command的,当然也可以之间在定义adapter的时候写入sql语句和connection对象
// 连线strstring connectString = "Server=dataserver; Database=FormericaOE; User ID=xxx; Password=xxx; ";// 建构 sqlConnection连线物件SqlConnection conn = new SqlConnection(connectString);string selectstr = "SELECT MAX(SN)" + "FROM[FormericaOE].[dbo].[Table_Friber_SN]";SqlDataAdapter da = new SqlDataAdapter(selectstr, connectString);DS.Clear(); //先清空 DataTableda.Fill(DS); //用SqlDataAdapter 填入 DS
想要把数据显示出来就不得不用到adapter来给dataset传值而command不能直接传值给dataset可以这样理解: DataSet用来装表的集合,裏面可以装从SqlDataAdapter中返回的一系列的DataTable
如果返回的有多张表,那么我们可以通过索引的方式来找到想要的表:
DataTable dt = ds.Tables[0];或DataTable dt = ds.Tables["products"];
DataSet可以直接做爲数据控件的数据源,也可以从中获取表或表的视图来做爲数据源.如:
this.DataList1.DataSource = dt;this.DataList2.DataSource = dt.Tables[0];this.Datalist3.DataSource = dt.Tables[0].DefaultView;这三句的效果都是一样的.