Command对象的ExecuteNonQuery()方法执行任何不从数据库返回结果集的命令,包括SQL SELECT、UPDATE、DELETE语句、没有返回数值的存储过程、CREATE TABLE和CREATE INDEX之类的DDL语句
 
1、下面代码使用ExecuteNonQuery执行DML(INSERT、UPDATE、DELETE)语句
 
string oSql=“insert into verify(userid,password,name,level,station,dept)  values(‘LH’,’1’,’李宏‘,’系统管理员‘,’部长‘,’信息部‘)”;
string oSql=“update verify set userid=‘LH’,name=‘李宏’,level=‘系统管理员’,station=‘部长’,dept=‘信息组’)   where id=‘001’”;
string oSql=“insert into verify(delete from verify where id=‘001’”;
SqlCommand comm=new SqlCommand(oSql,con);//创建和声明Command对象
con.Open();//在调用方法前打开数据库连接,可以减少数据库连接所花的时间,节省数据库资源。
int jl=comm.ExecuteNonQuery();//执行SQL语句并返回的int值是命令影响的数据库行数 jl的值为1
con.Close();//关闭数据库连接
 
2、下面代码使用ExecuteNonQuery执行DDL(CREATE TABLE、ALTER TABLE、DROP TABLE)语句
 
string oSql=“CREATE TABLE dept(ID uniqueidentifier not null,dept varchar(10) not null)”;
string oSql=“ALTER TABLE dept ADD dept_explain text”;
string oSql=“ALTER TABLE dept ALTER COLUMN dept_explain 
varchar(255)”;
string oSql=“ALTER TABLE dept DROP COLUMN dept_explain”;
string oSql=“ALTER TABLE dept WITH NOCHECK ADD
CONSTRAINT [DF_dept_ID] DEFAULT (newid()) FOR [ID]”;
string oSql=“DROP TABLE DEPT”;
SqlCommand comm=new SqlCommand(oSql,con); //创建和声明Command对象
con.Open();//在调用方法前打开数据库连接,可以减少数据库连接所花的时间,节省数据库资源。
int jl=comm.ExecuteNonQuery();//执行SQL语句并返回的int值为-1 因为DDL语句不影响的数据库行数
con.Close();//关闭数据库连接