3
public void SQLconnect() {
try {
  System.out.println("Connecting to MySQL database...");
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  String conn = "jdbc:mysql://" + this.SQL_HOST/* + ":" + this.SQL_PORT */
      + "/" + this.SQL_DATA;
  this.con = DriverManager
      .getConnection(conn, this.SQL_USER, this.SQL_PASS);
} catch (ClassNotFoundException ex) {
  System.err.println("No MySQL driver found!");
} catch (SQLException ex) {
  System.err
      .println("Error while fetching MySQL connection!");
} catch (Exception ex) {
  System.err
      .println("Unknown error while fetching MySQL connection.");
 }
}

This is java, Can I use the connection "con" to connect to my MySql database from different threads? Or is this not thread safe.

And if its not thread safe, How should I do this?

Andrew
  • 57
  • 3
  • 6

2 Answers2

2

It is not thread safe. You have to get a new connection every time you need one. It should never be a member variable, always a local variable or method parameter.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Not technically correct: see [this question](http://stackoverflow.com/questions/1531073/is-java-sql-connection-thread-safe), which has answers which explain this more precisely. – Sam Goldberg Feb 21 '13 at 18:58
1

In JDBC, the Connection interface is not thread safe, you have to manage it your self. For example, you need to open new connection every time and close it.

For convenience, you can use Connection Pool, because manage connection's open and close is a boring task; with connection pool, you just get an connection and put it back, the pool will manage all connections it opened and reuse them. You can checkout C3P0 or DBCP

donnior
  • 1,055
  • 1
  • 9
  • 12
  • It may be boring but the interface to a connection pool is identical to the interface that gives you a non-pooled connection. – user207421 Aug 19 '12 at 05:36