对重复要执行的语句,使用这个方法可以提高执行效率。使用这个方法时候必须声名Parameters的三个参数,否则会产生异常。
且看下面代码:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
private
void
button1_Click(
object
sender, EventArgs e)
{
Stopwatch sw = new Stopwatch();
sw.Start();
using (SqlConnection con = getCon())
{
con.Open();
SqlCommand com = new SqlCommand( null , con);
com.CommandText = " INSERT INTO tb_user ([Username],[Password]) VALUES(@UserName, @PassWord) " ;
com.Parameters.Add( " @UserName " , SqlDbType.NChar, 20 );
com.Parameters.Add( " @Password " , SqlDbType.NChar, 20 );
com.Prepare();
for ( int i = 0 ; i < 1 ; i ++ )
{
com.Parameters[ 0 ].Value = " UserName " + i;
com.Parameters[ 1 ].Value = " Password " + i;
com.ExecuteNonQuery();
}
}
sw.Stop();
this .label1.Text = sw.ElapsedMilliseconds.ToString();
}
private SqlConnection getCon()
{
SqlConnection con = new SqlConnection( " Data Source=ITSW;Initial Catalog=CMSDEMO;User ID=sa;Password=xxsecr " );
return con;
}
{
Stopwatch sw = new Stopwatch();
sw.Start();
using (SqlConnection con = getCon())
{
con.Open();
SqlCommand com = new SqlCommand( null , con);
com.CommandText = " INSERT INTO tb_user ([Username],[Password]) VALUES(@UserName, @PassWord) " ;
com.Parameters.Add( " @UserName " , SqlDbType.NChar, 20 );
com.Parameters.Add( " @Password " , SqlDbType.NChar, 20 );
com.Prepare();
for ( int i = 0 ; i < 1 ; i ++ )
{
com.Parameters[ 0 ].Value = " UserName " + i;
com.Parameters[ 1 ].Value = " Password " + i;
com.ExecuteNonQuery();
}
}
sw.Stop();
this .label1.Text = sw.ElapsedMilliseconds.ToString();
}
private SqlConnection getCon()
{
SqlConnection con = new SqlConnection( " Data Source=ITSW;Initial Catalog=CMSDEMO;User ID=sa;Password=xxsecr " );
return con;
}
运行十次,在我的电脑上取得结果平均值大约为4150左右。
如果没有使用这个方法,结果平均值大约为4500左右。