多个SQL查询asp.net C# [英] Multiple SQL queries asp.net c#
本文介绍了多个SQL查询asp.net C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要运行一个函数里面几个查询,我将不得不为每一个新的SqlConnection?或有一个连接,但不同SqlCommands的作品吗?
谢谢,
编辑:将这项工作?
使用(SqlConnection的康恩=新的SqlConnection(的connectionString))
{
conn.Open(); 使用(CMD的SqlCommand =新的SqlCommand(QUERY1,康涅狄格州))
{
cmd.ExecuteNonQuery();
} 使用(CMD的SqlCommand =新的SqlCommand(QUERY2,康涅狄格州))
{
cmd.ExecuteNonQuery();
} 使用(CMD的SqlCommand =新的SqlCommand(QUERY3,康涅狄格州))
{
cmd.ExecuteNonQuery();
} }
解决方案
使用的 MDSN文档作为基础:
使用(SqlConnection的连接=新的SqlConnection(的connectionString))
{
connection.Open(); 字符串SQL1 =SELECT ID,名字,姓氏FROM VP_PERSON
字符串SQL2 =选择地址,城市,州,code从VP_ADDRESS 使用(的SqlCommand命令=新的SqlCommand(SQL1,连接))
{
//命令1
使用(SqlDataReader的读卡器= Command.ExecuteReader却())
{
// reader.Read迭代等
} } //命令配置。 使用(的SqlCommand命令=新的SqlCommand(SQL2,连接))
{ //命令1
使用(SqlDataReader的读卡器= Command.ExecuteReader却())
{
// reader.Read迭代等
} } //命令配置。 //如果你不使用使用您SqlCommands你需要处理掉
//调用command.Dispose();在命令大功告成了。} //关闭SqlConnection将被全部销毁
I need to run several queries inside one function, will I have to create a new SqlConnection for each? Or having one connection but different SqlCommands works too?
Thanks,
EDIT: Will this work?
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query1, conn))
{
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(query2, conn))
{
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand(query3, conn))
{
cmd.ExecuteNonQuery();
}
}
解决方案
Using the MDSN Documentation as a base:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql1 = "SELECT ID,FirstName,LastName FROM VP_PERSON";
string sql2 = "SELECT Address,City,State,Code FROM VP_ADDRESS";
using (SqlCommand command = new SqlCommand(sql1,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
using (SqlCommand command = new SqlCommand(sql2,connection))
{
//Command 1
using (SqlDataReader reader = command.ExecuteReader())
{
// reader.Read iteration etc
}
} // command is disposed.
// If you don't using using on your SqlCommands you need to dispose of them
// by calling command.Dispose(); on the command after you're done.
} // the SqlConnection will be disposed
这篇关于多个SQL查询asp.net C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文