首页 新闻 会员 周边 捐助

多线程 SQL语句

0
悬赏园豆:50 [已解决问题] 解决于 2011-11-17 13:35

多线程处理Sql语句,也就是说一个线程上处理一个语句,如何实现?请高手们帮忙,指教。

答应不爱你的主页 答应不爱你 | 初学一级 | 园豆:3
提问于:2011-11-16 11:09
< >
分享
最佳答案
0

没什么的,最主要的是每个线程肯定有一个独立的Connection。

    class SqlExecutor
{
private string connectionString;
private string commandText;
private Thread workthread;

public SqlExecutor(string commandText, string connectionString)
{
this.commandText = commandText;
this.connectionString = connectionString;
}

public void DoExecute()
{
workthread = new Thread(new ThreadStart(this.ExecuteSql));
workthread.Start();
}

private void ExecuteSql()
{
using (DbConnection connection = new SqlConnection(connectionString))
using (DbCommand command = new SqlCommand())
{
connection.Open();
command.Connection = connection;
command.CommandText = commandText;
command.ExecuteNonQuery();
connection.Close();
}
Console.WriteLine("Execute '{0}' completed", commandText);
}

public void Join()
{
if (workthread != null)
if (workthread.IsAlive) workthread.Join();
}
}

static void Main(string[] args)
{
string connectionString = "你自己的连接串";
SqlExecutor[] executors = new SqlExecutor[]{
new SqlExecutor("Select 1", connectionString),
new SqlExecutor("Select @@version", connectionString)
};
foreach (SqlExecutor executor in executors)
{
executor.DoExecute();
}
foreach (SqlExecutor executor in executors)
{
executor.Join();
}
Console.ReadLine();
}
收获园豆:30
ChatinCode | 老鸟四级 |园豆:2272 | 2011-11-16 12:47

异常自己捕获

ChatinCode | 园豆:2272 (老鸟四级) | 2011-11-16 12:49

谢谢您的指导。

答应不爱你 | 园豆:3 (初学一级) | 2011-11-17 13:28
其他回答(2)
0

Thread workthread = new Thread(new ThreadStart(this.ExecuteSql));
 workthread.Start();

收获园豆:10
悟行 | 园豆:12559 (专家六级) | 2011-11-16 13:53

感谢!

支持(0) 反对(0) 答应不爱你 | 园豆:3 (初学一级) | 2011-11-17 13:29
0

就是这样开辟线程,执行SQL语句就是了。

收获园豆:10
[CC] | 园豆:61 (初学一级) | 2011-11-17 10:02
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册