使用多线程连接到MySQL数据库 [英] Connect to MySQL DB using multi-threading

查看:530
本文介绍了使用多线程连接到MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个处理数据库的Java代码,并且想在我的应用程序中使用多线程.每个线程都假定运行一个函数,该函数包含对数据库的插入.我的问题是:我应该在哪里放置以下语句:

If I have a java code that deals with database and I want to use multi-threading in my application. Each thread suppose to run a function that contains insertion to the database. My question is: Where should I place the following statements:

Connection con = DriverManager.getConnection (dbUrl);
query = " insert into schema.table values (default,?,?)";   
preparedStmt = con.prepareStatement(query);

我应该将它们放置在run中,以便每个线程都执行它们吗?还是在Main中只执行一次?还是在run函数调用的函数内部?当我有多线程时,我需要知道插入数据库的正确方法.谢谢.

Should I place them in the run so every thread execute them? or in the Main so they are executed once only? or inside the function that is called by the run function ? I need to know the right method to insert to Database when I have multi-threads. Thanks.

推荐答案

您应该考虑创建一个ConnectionPool并从该池中获取与数据库相关的工作的连接.

You should consider creating a ConnectionPool and get connection from this pool for your database related work.

您可能会喜欢以下两个链接:

The following two links might be of interest to you:

连接池
Apache Commons DBCP

编辑 感谢@MJB指出这一点:
BoneCP 是另一个

Edit Thanks to @MJB for pointing this one out:
c3p0 is another one that is pretty good.
BoneCP is another one

但是,总而言之,最简单的一点是:您需要实现连接池.您选择哪一个完全取决于您的决定并根据您的要求.

But at the end of the day, the simple point is this: You need to implement connection pooling. Which one you choose is totally your decision and based on your requirements.

这篇关于使用多线程连接到MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆