C#之执行SQL语句:Command对象

在使用ADO.NET中的连接数据库:Connection对象连接上数据库之后,我们下面所做的就是对数据库中的数据进行操作。在ADO.NET中,是通过执行SQL语句:Command对象来对数据进行操作

下面的所有的例子均使用下面的数据库:

Command对象概述

Command对象最主要的工作是通过Connection对象对数据源下达操作数据库的命令。Command对象有许多属性,,但是常用的属性为:

属性

说明

ActiveConnection设定要透过哪个连接对象下命令

CommandBehavior设定Command对象的动作模式

CommandType(Text\TableDirect\StoredProcedure)命令类型(SQL语句,完整表达句,存储过程)

CommandText要下达至数据源的命令

CommandTimeout出错时等待时间

Parameters参数集合

RccordsAffected受影响的记录数

例一,创建一个SqlCommand对象comText,并设置出错时等待时间为2秒。完整的代码为:

<span style="font-size:18px;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.SqlClient;//引入命名空间namespace ConsoleApplication1{class Program{static void Main(string[] args){string conStr = "server=.;user=sa;pwd=123456;database=CustomerManagement";//连接字符串SqlConnection conText = new SqlConnection(conStr);//创建Connection对象try{conText.Open();//打开数据库string sql = "select * from manager";//创建统计语句SqlCommand comText = new SqlCommand(sql, conText);//创建Command对象comText.CommandTimeout = 2;//设置等待时间Console.WriteLine("创建Command成功");}catch (Exception ex)//创建检查Exception对象{Console.WriteLine(ex.Message.ToString());//输出错误信息}finally{conText.Close();//关闭连接}Console.ReadLine();}}}</span>

运行结果为:

执行SQL语句

定义好命令后就应当执行命令,Command对象执行命令提供了三种方法。

方法返回值描述

ExecuteNonQuery()不返回任何结果

ExecuteReader()返回一个IDataReader

ExecuteScalar()返回一个值

1,ExecuteNonQuery方法

这个方法没有返回任何结果,所以一般用于updata,delete,insert语句中。

例二,通过ExecuteNonQuery方法更改CustomerManagement数据库中的manager数据表中id为1的用户的密码。完整的代码为:

<span style="font-size:18px;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Data.SqlClient;//引入命名空间namespace ConsoleApplication1{class Program{static void Main(string[] args){string conStr = "server=.;user=sa;pwd=123456;database=CustomerManagement";//连接字符串SqlConnection conText = new SqlConnection(conStr);//创建Connection对象try{conText.Open();//打开数据库string sql = "update manager set userPwd=123456789 where id=1";//创建修改语句SqlCommand comText = new SqlCommand(sql, conText);//创建Command对象comText.ExecuteNonQuery();//执行命令Console.WriteLine("更改成功");}catch (Exception ex)//创建检查Exception对象{Console.WriteLine(ex.Message.ToString());//输出错误信息}finally{conText.Close();//关闭连接}Console.ReadLine();}}}</span>

运行时出现这样的结果:

编译时并没有出现错误,仔细检查后才知道是update语句拼写错误,就因为一个小小的拼写错误,费了半天劲才找到,把updata改成update即可,再运行的结果为:

在CustomerManagement数据库中的manager数据表的内容已更改:

就是对虚怀若谷谦虚谨慎八个字真正理解的人,

C#之执行SQL语句:Command对象

相关文章:

你感兴趣的文章:

标签云: