词条 | sqlcommand |
释义 | SqlCommand类的属性(1.CommandText 2. CommandType 3.Connection 4.CommandTimeOut) SqlCommand类的方法(1.ExecuteNonQuery(); 2.ExecuteReader(); 3.ExecuteScaler();) Sqlcommand介绍表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程。无法继承此类。 命名空间: System.Data.SqlClient 程序集: System.Data(在 System.Data.dll 中) C#: public sealed class SqlCommand : DbCommand, ICloneable 当创建 SqlCommand 的实例时,读/写属性将被设置为它们的初始值。 您可以重置 CommandText 属性并重复使用 SqlCommand 对象。但是,在执行新的命令或先前命令之前,必须关闭 SqlDataReader。如果执行 SqlCommand 的方法生成 SqlException,那么当严重级别小于等于 19 时,SqlConnection 将仍保持打开状态。当严重级别大于等于 20 时,服务器通常会关闭 SqlConnection。但是,用户可以重新打开连接并继续。 Sqlcommand实例private static void ReadOrderData(string connectionString) { //要执行的Sql语句 string queryString ="SELECT OrderID, CustomerID FROM dbo.Orders;"; using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand( queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); try { while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); } } finally { // Always call Close when done reading. reader.Close(); } } } string str = "server='(local)';database='mytable';uid='sa';pwd='sa'"; SqlConnection con = new SqlConnection(str); //创建连接对象 con.Open(); //打开连接 其中,str是数据连接字串,用来初始化Connection对象,说明如何连接数据库,当数据库连接完毕后,可以使用Open方法打开数据连接。完成数据库连接后,需创建一个新的Command对象,示例代码如下所示。 SqlCommand cmd = new SqlCommand("insert into mynews value ('插入一条新数据')", con); Command对象的构造函数的参数有两个,一个是需要执行的SQL语句,另一个是数据库连接对象。创建Command对象后,就可以执行SQL命令,执行后完成并关闭数据连接,示例代码如下所示。 cmd.ExecuteNonQuery(); //执行SQL命令 con.Close(); //关闭连接 SqlCommand类的属性1.CommandText获取或设置要对数据源执行的Transact—SQL语句或存储过程。 2. CommandType获取或设置一个值,该值指示如何解释CommandText属性。 3.Connection获取或设置SqlCommand的实例使用的SqlConnection。 4.CommandTimeOut获取或设置在终止执行命令的尝试并生成错误之前的等待时间。 SqlCommand类的方法1.ExecuteNonQuery();它的返回值类型为int型。多用于执行增加,删除,修改数据。返回受影响的行数。 2.ExecuteReader();它的返回类型为SqlDataReader。此方法用于用户进行的查询操作。使用SqlDataReader对象的Read();方法进行逐行读取。 例如: SqlCommand comm =new SqlCommand("select * from CGSZ where cid="+id,conn); SqlDataReader reder=comm.ExecuteReader(); while(reder.Read()) { //读出内容列 string str=reder["cname"].ToString(); //读取分类列 string str1=reder["ckind"].ToString(); //分别为文本框加载数据 this.txtContent.Text = str; this.txtClass.Text = str1; } 其中的读取数据列的时候。除了使用reder["列名"].ToString();还可以使用reder[索引].ToSting();<注意:这里的索引指的是数据库中列的索引。从0开始。> 3.ExecuteScaler();它的返回值类型多为int类型。它返回的多为执行select查询。得到的返回结果为一个值的情况,比如使用count函数求表中记录个数或者使用sum函数求和等。 |
随便看 |
百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。