SqlCommand 对象-ExecuteNonQuery() 方法的使用

作者:晨星 来源: 日期:2008-6-17

版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://chenxing.blog.51cto.com/240526/45011

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'";

//创建和声明Command对象con.Open();
//在调用方法前打开数据库连接,可以减少数据库连接所花的时间,节省数据库资源。


SqlCommand comm=new SqlCommand(oSql, con);
//执行SQL语句并返回的int值是命令影响的数据库行数 jl的值为1
int jl=comm.ExecuteNonQuery();
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();//关闭数据库连接

相关阅读

相关文章