So I'm trying to create a discord bot that has simple access to a database for printing out values, my code currently will print the values to the discord server but it repeats them 5 times.
Bot functionality class:
private MySQLAccess sql = new MySQLAccess();
public static void main(String[] args) throws Exception {
JDABuilder ark = new JDABuilder(AccountType.BOT);
ark.setToken("insert_discord_token_here");
ark.addEventListener(new MessageListener());
ark.buildAsync();
}
#Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getAuthor().isBot()) return;
Message msg = e.getMessage();
String str = msg.getContentRaw();
//Ping pong
if (str.equalsIgnoreCase("!ping")) {
e.getChannel().sendMessage("Pong!").queue();
}
//Bal check
if (str.contains("!bal")) {
String user = str.substring(5);
System.out.println(user);
try {
sql.readDataBase(e.getChannel(), user);
} catch (Exception e1) {
}
}
}
Database Access Class:
private Connection connect = null;
private Statement statement = null;
private ResultSet resultSet = null;
private final String user = "pass";
private final String pass = "user";
public void readDataBase(MessageChannel msg, String username) throws Exception {
//Retrieve data and search for username
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/serverusers?allowPublicKeyRetrieval=true&useSSL=false", user, pass);
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from serverusers.userinfo where user=\"" + username + "\"");
writeResultSet(resultSet, msg);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet, MessageChannel msg) throws SQLException {
// Check resultSet and print its contents
if (resultSet.next()) {
String user = resultSet.getString(2);
Double website = resultSet.getDouble(3);
msg.sendMessage("User: " + user).queue();
msg.sendMessage("Bank Amount: " + website).queue();
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}
When the program is run it finds the correct data that I'm looking for and the search function is fine, but for some odd reason the program will spit the same username and balance out 5 times.
Screenshot of Discord Bot
The common mistake here is that you run the program multiple times, each instance then responds accordingly with the same thing. You can check if that is the case by opening the task manager and looking for java processes. This often occurs with developers using the Eclipse IDE because of the console hiding other processes behind a drop-down menu on the console.
Related
To get an idea of what the basic structure looks like, I downloaded a money system including MySQL from Spigot and looked at the code.
public static boolean playerExists(String uuid) {
try {
ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
if (rs.next())
return (rs.getString("UUID") != null);
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public static void createPlayer(String uuid) {
if (!playerExists(uuid))
Simplecoinsystem.mysql.update("INSERT INTO CoinData (UUID, COINS) VALUES ('" + uuid +
"', '" + Simplecoinsystem.getInstance().getConfig().getInt("startcoins") + "');");
}
public static Integer getCoins(String uuid) {
Integer i = Integer.valueOf(0);
if (playerExists(uuid)) {
try {
ResultSet rs = Simplecoinsystem.mysql.query("SELECT * FROM CoinData WHERE UUID= '" + uuid + "'");
if (rs.next())
Integer.valueOf(rs.getInt("COINS"));
i = Integer.valueOf(rs.getInt("COINS"));
} catch (SQLException e) {
e.printStackTrace();
}
} else {
createPlayer(uuid);
}
return i;
}
public static void setCoins(String uuid, Integer coins) {
if (playerExists(uuid)) {
Simplecoinsystem.mysql.update("UPDATE CoinData SET COINS= '" + coins + "' WHERE UUID= '" + uuid + "';");
} else {
createPlayer(uuid);
}
}
Am I correct that it is actually impractical to create a new entry with the uuid of the non-existent player after each query of the coins if the player does not exist?
Wouldn't this make it possible to flood the database with thousands of unnecessary entries by issuing, for example, a "/money (player)" command as an evil player/admin?
Couldn't I just ask when entering the server if the uuid is already stored and if not, just enter it? This way there would only be entries from players who have already been on the server before. Whether this needs great server performance, I'm not sure.
This is my first own MySQL class.
public class MySQL {
private String host, database, user, password;
private int port;
private Connection con;
public MySQL(String host, int port, String database, String user, String password) {
this.host = host;
this.port = port;
this.database = database;
this.user = user;
this.password = password;
connect();
}
public void connect() {
try {
con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", user, password);
System.out.println("&cDie MySQL Verbindung wurde erfolgreich aufgebaut!");
} catch (SQLException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
if(this.con != null) {
this.con.close();
System.out.println("§cDie MySQL Verbindung wurde erfolgreich beendet!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void update(String query) {
try {
Statement st = con.createStatement();
st.executeUpdate(query);
st.close();
} catch (Exception e) {
e.printStackTrace();
connect();
}
}
public ResultSet qry(String query) {
ResultSet rs = null;
try {
Statement st = con.createStatement();
rs = st.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
connect();
}
return rs;
}
public Connection getConnection() {
return this.con;
}
}
Except for this part, both MySQL classes are built relatively the same.
This is the part that is in the MySQL class of the Spigot plugin.
Your code have multiple issues.
When the connection will be closed, next time you will have an error. In your Mysql class, I suggest you to do:
public Connection getConnection() {
if(con == null || con.isClosed())
connect();
return con;
}
Then, use it in all method like getConnection().prepareStatement().
You can be attacked with SQL Injection. To fix this, try to do something like:
PreparedStatement st = con.prepareStatement("SELECT * FROM CoinData WHERE UUID = ?");
st.setString(1, uuid.toString()); // Yes it start at 1 !!
st.executeUpdate();
With this, even with all values, you can't be attacked with injections.
You will have an error while getting coins:
if (rs.next()) // go to good line
Integer.valueOf(rs.getInt("COINS")); // useless convertion
i = Integer.valueOf(rs.getInt("COINS")); // error if no line.
You can just do:
if(rs.next())
i = rs.getInt("COINS");
If the column "UUID" is unique, you will not have duplicated lines.
Finally, about performance, it's better to do it one time: at login, instead of all time. You can also create an object stored in an hashmap to easier access to it, without using SQL, like that:
public static HashMap<UUID, Integer> coinsByPlayer = new HashMap<>();
OR:
public static HashMap<UUID, MyObject> coinsByPlayer = new HashMap<>();
public class MyObject {
private int coins = 0;
public MyObject(UUID uuid) {
// make SQL request to get data
}
public int getCoins() {
return coins;
}
public void setCoins(int next){
coins = next;
// here make "UPDATE" sql query
}
}
What do you say? Is it ok with the try/catch function? #Elikill58
public Connection getConnection() {
try {
if(con == null || con.isClosed()) {
connect();
}
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
edit:
public Connection getConnection_one() throws SQLException {
if(con == null || con.isClosed()) {
connect();
return con;
} else {
return con;
}
}
I connect to Hive and get id's of my data from row of table. Problems does not happens, when I connect to hive, send request and get response. But when i get id's from ResultSet i get an exception: org.apache.thrift.transport.TTransportException: SASL authentication not complete. Why does this exception arise and what needs to be done to avoid it? Sorry for my bad english.
It's my subsidiary class to create hive connection and send requests:
public class HiveDataSearcher implements AutoCloseable {
private static final String hiveDriverName = "org.apache.hive.jdbc.HiveDriver";
static {
try {
Class.forName(hiveDriverName);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private Connection hiveConnection;
private String tableName;
private String whereBody;
public HiveDataSearcher(String url, String login, String password) {
try {
hiveConnection = DriverManager.getConnection(url, login, password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
this.tableName = "";
this.whereBody = "";
}
public HiveDataSearcher(Connection hiveConnection) {
Objects.requireNonNull(hiveConnection, "hiveConnection");
this.hiveConnection = hiveConnection;
this.tableName = "";
this.whereBody = "";
}
public String getTableName() {
return tableName;
}
public HiveDataSearcher setTableName(String tableName) {
Objects.requireNonNull(tableName, "tableName");
this.tableName = tableName;
return this;
}
public String getWhereBody() {
return whereBody;
}
public HiveDataSearcher setWhereBody(String whereBody) {
Objects.requireNonNull(whereBody, "whereBody");
this.whereBody = whereBody;
return this;
}
public ResultSet select(String ... selectParams) {
return select(Arrays.asList(selectParams));
}
public ResultSet select(Iterable<String> selectParams) {
String request = prepareRequest(selectParams);
ResultSet response;
try {
response = hiveConnection
.createStatement()
.executeQuery(request);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return response;
}
private String prepareRequest(Iterable<String> selectParams) {
return new StringBuilder()
.append("select").append(' ').append(selectParamsToHiveFormat(selectParams)).append(' ')
.append("from").append(' ').append(tableName).append(' ')
.append("where").append(' ').append(whereBody)
.toString();
}
private String selectParamsToHiveFormat(Iterable<String> selectParams) {
StringBuilder formattedSelectParams = new StringBuilder();
for (String selectedParam : selectParams) {
formattedSelectParams.append('\'').append(selectedParam).append('\'').append(',');
}
if (formattedSelectParams.length() == 0) {
formattedSelectParams.append('*');
} else {
formattedSelectParams.deleteCharAt(formattedSelectParams.length() - 1);
}
return formattedSelectParams.toString();
}
public void close() {
if (hiveConnection != null) {
try {
hiveConnection.close();
} catch (SQLException e) {
//nothing to do, just close connection
} finally {
hiveConnection = null;
}
}
}
}
This is the code in which i connect to hive:
private static final String HIVE_URL = <hive url>;
private static final String HIVE_LOGIN = <hive login>;
private static final String HIVE_PASSWORD = <hive password>;
private static final String[] SEARCH_FIELDS = new String[] {"rowkey"};
private List<String> getIdsFromHive(String tableName, String whereBody) {
ResultSet hiveResponse;
try (HiveDataSearcher searcher = new HiveDataSearcher(HIVE_URL, HIVE_LOGIN, HIVE_PASSWORD)) {
hiveResponse = searcher
.setTableName(tableName)
.setWhereBody(whereBody)
.select(SEARCH_FIELDS);
}
List<String> ids = new ArrayList<>();
try {
while (hiveResponse.next()) { // in this place throw TTransportException
ids.add(hiveResponse.getString(SEARCH_FIELDS[0]));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return ids;
}
In my case, the reason for this exception is closed the connection before closed the statement. So I suggest you to check whether you has maintain the connection correctly.
Here is my code, wish it will inspire you something:
Wrong code, close connection before closing the statement:
Connection connection = null;
Statement statement = null;
try {
connection = HIVEUTILS.getConnection();
statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS tbl1");
statement.execute("CREATE TABLE `tbl1` (`id` int)");
statement.execute("INSERT INTO tbl1 VALUES(1)");
}finally {
if (connection != null){
connection.close();
}
if (statement != null){
statement.close(); // exception occur here.
}
}
The correct order of closing is: close resultSet(if any) -> close statement -> close connection.
Connection connection = null;
Statement statement = null;
try {
connection = HIVEUTILS.getConnection();
statement = connection.createStatement();
statement.execute("DROP TABLE IF EXISTS tbl1");
statement.execute("CREATE TABLE `tbl1` (`id` int)");
statement.execute("INSERT INTO tbl1 VALUES(1)");
}finally {
if (statement != null){
statement.close(); // change the order
}
if (connection != null){
connection.close();
}
}
I'm working on an application that records do my MySql database on my server. Every time I want to use the database, get the existing connection, if not, I think for the first time. When I do an insert or select, works very well, but followed that consultation, when it ends, I can never regain the connection and do not return to consultations.
My class of Database
public class Database {
/**
* Gets just one instance of the class
* Connects on construct
* #returns connection
*/
private Connection _conn = null;
private long timer;
//singleton code
private static Database DatabaseObject;
private Database() {}
public static Database connect() {
if (DatabaseObject == null)
DatabaseObject = new Database();
return DatabaseObject._connect();
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
//end singleton code
/**
* Connects with the defined parameters on Config
* Prevents re-connection if object was already connected
* #throws SQLException
*/
private Database _connect() {
try {
if (this._conn == null || !this._conn.isValid(0)) {
try {
Class.forName("com.mysql.jdbc.Driver");
Properties connProps = new Properties();
connProps.put("user", Config.Config.DB_USER);
connProps.put("password", Config.Config.DB_PASS);
this._conn = DriverManager.
getConnection("jdbc:" + Config.Config.DB_DBMS + "://" + Config.Config.DB_HOST + ":"
+ Config.Config.DB_PORT + "/" + Config.Config.DB_NAME, Config.Config.DB_USER, Config.Config.DB_PASS);
timer = System.currentTimeMillis();
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Could not connect to DB");
e.printStackTrace();
}
} else {
try {
long tmp = System.currentTimeMillis() - timer;
if (tmp > 1200000) { //3600000 one hour ; 1200000 twenty minutes
System.out.println("Forcing reconnection ("+tmp+" milliseconds passed since last connection)");
this.close();
this._connect();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Forcing reconnection");
this._conn = null;
this._connect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
/**
* Closes connections
* This has to be invoked when database connection is no longer needed
* #throws SQLException
*/
public void close() throws SQLException {
if (this._conn != null) {
this._conn.close();
this._conn = null;
}
}
/**
* Getter for connection
* #return
*/
public Connection get() {
return this._conn;
}
}
The following function I make a query:
private Statement sment = null;
private PreparedStatement psment = null;
private ResultSet rset = null;
public boolean existsByNameAndUserId(String md5, int userId, int eventId) {
Connection conn = Database.connect().get();
try {
psment = conn.prepareStatement("SELECT * FROM files "
+ "WHERE user_id = ? AND md5 = ? AND evento_id = ?");
psment.setInt(1, userId);
psment.setString(2, md5);
psment.setInt(3, eventId);
rset = psment.executeQuery();
if (rset.next()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void close() {
try { if (rset != null) rset.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (psment != null) psment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
try { if (sment != null) sment.close(); } catch (Exception e) {System.out.println(e.getMessage());};
}
And in the next, I call the above function to find out whether or not a record with these characteristics, if not, I do an insert.
String SQL_INSERT = "INSERT INTO files (evento_id, user_id, path, thumb, preview, width, height, md5, numero_corredor, created, modified) "
+ "VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())";
public void save(List<components.File.Schema> files) throws SQLException {
try (
Connection conn = Database.connect().get();
PreparedStatement statement = conn.prepareStatement(SQL_INSERT);
) {
int i = 0;
for (components.File.Schema file : files) {
if(!existsByNameAndUserId(file.getMd5(), file.getUserId(), file.getEventId())){
statement.setInt(1, file.getEventId());
statement.setInt(2, file.getUserId());
statement.setString(3, file.getPath());
statement.setString(4, file.getPreview());
statement.setString(5, file.getThumb());
statement.setInt(6, file.getWidth());
statement.setInt(7, file.getHeight());
statement.setString(8, file.getMd5());
statement.setString(9, null);
statement.addBatch();
i++;
if (i % 1000 == 0 || i == files.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
}
Your issue is due to the fact that you put Connection conn = Database.connect().get() in a try-with-resources statement which is what you are supposed to do but it closes your connection and when you call it again as the method _connect() doesn't have a valid test, it doesn't create a new connection. The valid test is this._conn == null || !this._conn.isValid(0), indeed in your original test you call this._conn.isValid(0) which will returns false in our context since the connection is closed so it won't create a new connection which is not what we want here.
Response Update: The second part of the problem is the fact that in the save method you call existsByNameAndUserId which closes the current connection, you should only close the statement and let the method save close the connection.
I need help for my student project.
Currently I'm making a chat application using JavaFX, MQTT and Mysql.
I want to make an userlist (which user are online)
I tried this so that a new user would send a message through a special topic, and all will be "secretely" subscribing this topic it'll receive the message (using callback) and call the method insertingMysql() and updatingList(). But somehow it does not work.
This is where I give the username
public static void logging(String username) throws MqttException {
if(username != null && !username.isEmpty()) {
MysqlDatabase.insertingMysql(username);
window.close();
}
}
This is to add ListView
public static void addItem(String item) {
userList.getItems().add(item);
}
This is the part where I have problems with (I think)
public class MysqlDatabase {
static String topic_body = "chat";;
static String topic_ext = "userList";
static MqttCallback sqlCallback = new MqttCallback() {
#Override
public void connectionLost(Throwable thrwbl) {
}
#Override
public void messageArrived(String string, MqttMessage mm) throws Exception {
String username = new String(mm.getPayload());
System.out.println(username); // Checking
updatingList();
}
#Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
}
};
public static void sqlConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Connected");
}
public static void mqttConnection(String username) throws MqttException {
MqttClient sqlClient = new MqttClient("tcp://iot.eclipse.org:1883", username);
sqlClient.connect();
sqlClient.subscribe(topic_body + topic_ext + "#");
sqlClient.setCallback(sqlCallback);
MqttMessage sqlMessage = new MqttMessage();
sqlMessage.setPayload((username).getBytes());
sqlClient.publish(topic_body + "userlist", sqlMessage);
}
public static void insertingMysql(String username) throws MqttException {
sqlConnection();
String host = "jdbc:mysql://localhost/test";
String user = "root";
String password = "";
try {
Connection connect = DriverManager.getConnection(host, user, password);
PreparedStatement statement = (PreparedStatement) connect.prepareStatement("INSERT INTO chat_test(username)VALUES(?)");
statement.setString(1, username);
statement.executeUpdate();
statement.close();
System.out.println("Inserted to database!");
mqttConnection(username);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
public static void updatingList() {
sqlConnection();
String host = "jdbc:mysql://localhost/test";
String user = "root";
String password = "";
try {
Connection connect = DriverManager.getConnection(host, user, password);
PreparedStatement statement = (PreparedStatement) connect.prepareStatement("SELECT * FROM chat_test");
ResultSet rs = statement.executeQuery();
while(rs.next()) {
String uName = rs.getString("username");
System.out.println("Username: " + uName);
JavaFXChat.addItem(uName);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
}
There are 2 options here:
Database triggers. This is code that runs on the Database server when ever a table is changed. Normally these triggers are SQL statements but this blog (https://patternbuffer.wordpress.com/2012/09/14/triggering-shell-script-from-mysql/) post seams to talk about a plugin to support running a script that could send a MQTT message announcing the new user coming online.
Use MQTT messages and the Last Will and Testament feature. A users would publish a message to known topic then they come online, they would publish a similar message when going offline. The LWT can be used to automatically publish the offline message if the connetion drops due to problem. (details of LWT can be found here http://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament
So I'm quite new to Java and Derby. I'm using both with my Flex app on Tomcat 7.
When I make a call to Java from Flex the login function works fine but my getUserByUsername function does not.
public Boolean loginUser(String username, String password) throws Exception
{
Connection c = null;
String hashedPassword = new String();
try
{
c = ConnectionHelper.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT password FROM users WHERE username=?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
hashedPassword = rs.getString("password");
}
else
{
return false;
}
if(Password.check(password, hashedPassword))
{
return true;
}
else
{
return false;
}
}
catch (SQLException e)
{
e.printStackTrace();throw new DAOException(e);
}
finally
{
ConnectionHelper.closeConnection(c);
}
}
public User getUserByUsername(String username) throws DAOException
{
//System.out.println("Executing DAO.getUserByName:" + username);
User user = new User();
Connection c = null;
try
{
c = ConnectionHelper.getConnection();
PreparedStatement ps = c.prepareStatement("SELECT * FROM users WHERE username = ?");
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTeam(rs.getString("team"));
user.setScore(rs.getInt("score"));
}
}
catch (SQLException e)
{
e.printStackTrace();
throw new DAOException(e);
}
finally
{
ConnectionHelper.closeConnection(c);
}
return user;
}
The stack I get in Flex is useless as far as I can tell:
Flex Message (flex.messaging.messages.ErrorMessage) clientId = 8EB6D37B-7E0B-01B0->AA55-457722B9036C correlationId = A39E574F-CFC6-51FE-6CBE-451AF329E2F8 destination >= service messageId = 8EB6DF4C-650B-BDD7-7802-B813A61C8DC8 timestamp = >1401318734645 timeToLive = 0 body = null code = Server.Processing message = >services.DAOException : java.sql.SQLException: Failed to start database >'/Applications/blazeds/tomcat/webapps/testdrive/WEB-INF/database/game_db', see the next >exception for details. details = null rootCause = ASObject(23393258)>>{message=java.sql.SQLException: Failed to start database >'/Applications/blazeds/tomcat/webapps/testdrive/WEB-INF/database/game_db', see the next >exception for details., suppressed=[], localizedMessage=java.sql.SQLException: Failed to >start database '/Applications/blazeds/tomcat/webapps/testdrive/WEB->INF/database/game_db', see the next exception for details., cause=java.sql.SQLException} >body = null extendedData = null
My first thought was that it was just an error in my function (maybe someone else will notice it) but I've been looking through it for a couple hours and I can't see anything.
After that I thought maybe Derby had a problem with concurrent connections. I saw somewhere that Embedded JDBC can only handle one connection so I changed the driver from Embedded to Client which once again resulted in the login function working and the other an error saying the url in the connection was null. Any thoughts? Thanks ahead of time for any ideas.
EDIT:
package services;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.net.URLDecoder;
public class ConnectionHelper
{
private String url;
private static ConnectionHelper instance;
public String getUrl()
{
return url;
}
private ConnectionHelper()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String str = URLDecoder.decode(getClass().getClassLoader().getResource("services").toString(),"UTF-8");
str= str.substring(0, str.indexOf("classes/services"));
if ( str.startsWith("file:/C:",0)){
str=str.substring(6);
}
else{
str=str.substring(5);
}
url = "jdbc:derby:" + str + "database/game_db";
System.out.println("Database url "+url);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static ConnectionHelper getInstance()
{
if (instance == null)
instance = new ConnectionHelper();
return instance;
}
public static Connection getConnection() throws java.sql.SQLException
{
return DriverManager.getConnection(getInstance().getUrl());
}
public static void closeConnection(Connection c)
{
try
{
if (c != null)
{
c.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
There is NO problem with multiple connections in embedded mode. Full stop.
That said, what you may have come across, is that only one jvm process can access the Derby database files at a time. But that jvm may well have 1000s of threads each with their own connection to Derby (resources permitting, of course).