在前面介绍的例子中,SQL语句中每个列的值都被硬编码,例如: insert into dept(dept) values(‘信息组’)”,dept列的值被硬编码成“信息组”,如果执行多个INSERT语句,则硬编码这些列值既麻烦又低效。用参数点位符可以解决这个问题,参数可以在运行程序时指定不同的列值。
 
要执行包含参数的命令,使用下列步骤:
 
1、生成其中包含着SQL语句且带参数点位符的SqlCommand对象。这些点位符表示提供的参数的位置。
2、在SqlCommand对象中增加参数。
3、将参数设置为指定值
4、执行命令
 
下面代码使用ExecuteNonQuery执行带参数占位符的INSERT语句
con.Open();//在调用方法前打开数据库连接
SqlCommand comm=new con.CreateCommand();//创建和声明Command对象
comm.CommandText= “insert into dept(dept, dept_explain) values(@dept,@dept_explain)”;//设置参数
comm.Parameters.Add( “@dept”,SqlDbType.Varchar,10 );
comm.Parameters.Add( “@dept_explain”,SqlDbType.Text );
comm.Parameters[“@dept”].Value=“信息组”;
comm.Parameters[“@dept_explain”].Value=“负责整个分厂的计算机网络软件开发与维护”;
上面四行可以合并写成下面两行
comm.Parameters.Add( “@dept”,SqlDbType.Varchar,10).Value =“信息组”;
comm.Parameters.Add( “@dept_explain”,SqlDbType.Text ) .Value=“负责整
个分厂的计算机网络软件开发与维护”;
comm.ExecuteNonQuery();//执行SQL语句,如果执行SELECT语句,则要用
ExecuteReader()、ExecuteScalar()、ExecuteXmlReader()方法
con.Close();//关闭数据库连接
说明:可以将参数设置为null值,具体设置如下:
comm.Parameters[“@dept_explain].IsNullable=true;//IsNullable设置为true表示参数可以接受null值
comm.Parameters[“@dept_explain].Value=DbNull.Value;//DbNull.Value属性返回null值