Error getting connection to database from pool using in servlet - java

well I have a pretty awkward situation. I have a working database managers class, which works when I run it on the desktop version of it (Swing GUI), however, when I run the same class on the servlet, I get a strange error, that it can't get the connection. I am using database pooling for optimisation.
So the error looks as follows:
Error in Database Connection: Error getting connection to database - java.sql.SQLException: No suitable driver found for jdbc:sqlserver://isd.ktu.lt:1433;DatabaseName=LN2012_bakDB2
And the class with the methods involved looks like this:
package Core;
import DataTypes.Parameters;
import Interfaces.OutputInterface;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
*
* #author arturas
*/
public class DatabaseConnection {
String specificError = "Error in Database Connection: ";
OutputInterface gui = null;
boolean allowOutput = true;
GenericObjectPool connectionPool;
ConnectionFactory connectionFactory;
PoolableConnectionFactory poolableConnectionFactory;
PoolingDriver driver;
Connection con = null;
public DatabaseConnection(Parameters params) {
// parameters and the output
this.gui = params.getGui();
// activate database pool
connectionPool = new GenericObjectPool(null);
connectionFactory = new DriverManagerConnectionFactory(params.getDbAdr(), params.getDbUser(), params.getDbPass());
poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
driver = new PoolingDriver();
driver.registerPool("GenTreeDatabase", connectionPool);
}
public void openConn() {
if (allowOutput) gui.print("Getting connection to database");
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:GenTreeDatabase");
if (con != null) {
if (allowOutput) gui.print("Connection to database was successful");
}
} catch (SQLException ex) {
gui.err(specificError + "Error getting connection to database - " + ex);
}
}
public void closeConn() {
try {
con.close();
if (allowOutput) {
gui.print("Connection to database closed successfully");
}
} catch (SQLException ex) {
gui.err(specificError + ex);
}
}
The error appears when the try in method openConn is called.
Can anybody help me with this?

You are getting this error because there is no drivers in your classpath. Probably in your desktop application there were. You need to put driver's .jar file into your servlet container's global classpath or in your application classpath and it should work.
I prefer adding driver's jar into server global classpath, because there can be more than one application which will use the same .jar file to load drivers.

make sure of this
1) you should make sure that .jar library is compatabile with RDMS you are using
2) that you included the .jar for connection in your netbeans in
projectproperties-->libraries
3)copy the .jar into C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.26\lib
and this is important
if you dont have the driver in location you get not found error but
you get no suitable so i think the version must be incompatible so what version of sql server are you using...

Related

DB Derby Database stops functioning once connected to DBeaver

Here is my application's code to create the database, connect to it, and make a table in the database called Accounts.
package eportfolio.application;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JOptionPane;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* #author valeriomacpro
*/
public class HomePage extends javax.swing.JFrame {
public static String username;
public static String password;
public static int SelectedPost;
/**
* Creates new form HomePage
*/
public static boolean doesTableExists (String tableName, Connection conn)
throws SQLException {
DatabaseMetaData meta = conn.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
public HomePage() {
initComponents();
try
{
String databaseURL = "jdbc:derby:eportdatabase;create=true";
Connection con = DriverManager.getConnection(databaseURL);
Statement st = con.createStatement();
if (!doesTableExists("Accounts", con))
{
String sql = "CREATE TABLE Accounts (Username varchar(250), Password varchar(250)) ";
st.execute(sql);
System.out.println("Table Does Not Yet Exist!");
}
else if(doesTableExists("Accounts", con)) {
System.out.println("Table Already Exists!");
}
con.close();
} catch(SQLException e) {
do {
System.out.println("SQLState:" + e.getSQLState());
System.out.println("Error Code:" + e.getErrorCode());
System.out.println("Message:" + e.getMessage());
Throwable t = e.getCause();
while(t != null) {
System.out.println("Cause:" + t);
t = t.getCause();
}
e = e.getNextException();
} while (e != null);
}
}
Additionally, here is my code that interacts with the Accounts table.
try
{
String databaseURL = "jdbc:derby:eportdatabase;";
Connection con1 = DriverManager.getConnection(databaseURL);
Statement st = con1.createStatement();
String sql = " INSERT INTO Accounts VALUES ('"+txtNewUsername.getText()+"','"+txtNewPassword.getText()+"') ";
st.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Account Info Saved!");
txtNewUsername.setText("");
txtNewPassword.setText("");
txtNewConfirm.setText("");
}
When I run the application, the code works fine. However, if I open DBeaver and connect it to my database, then the following error message comes up. Does not come up if DBeaver is closed, even if it is connected to the database.
Message:Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XJ040: Failed to start database 'eportdatabase' with class loader jdk.internal.loader.ClassLoaders$AppClassLoader#45ee12a7, see the next exception for details.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
SQLState:XSDB6
Error Code:45000
Message:Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Cause:ERROR XSDB6: Another instance of Derby may have already booted the database /Users/(username)/NetBeansProjects/ePortfolio Application/eportdatabase.
Why is this? Am I connecting the Database to DBeaver incorrectly? Or am I coding the database incorrectly in Netbeans? It could be that my drivers and db derby version are old, but I have not been able to find help on that online either. Also important to know that the table does show up in DBeaver, but does not update. I have to delete the database folder in my application's folder every time I want to use the application with DBeaver open. Any help appreciated.
By using this line of code:
String databaseURL = "jdbc:derby:eportdatabase;";
you are using Derby in the "embedded" configuration. With Embedded Derby, only one Java application at a time can use the database. Other applications that try to use it concurrently are rejected with the message
Another instance of Derby may have already booted the database
as you saw when you tried it.
There are other configurations in which Derby can be deployed and run; specifically there is a Client-Server configuration in which multiple applications may all run as clients, and may connect to the same Derby server, allowing the applications to run concurrently.
To learn more about these aspects of Derby, start here: https://db.apache.org/derby/docs/10.15/getstart/cgsquck70629.html

Does MariaDB disconnect automatically or Should i have to disconnect Manually?

I got to use MariaDB for my University Project.
it's my first time doing it, so I dont't know well how to use and code JDBC Driver and mariaDB.
Now I'm implementing the code in many places while looking at examples.
As I see, All the examples seems to creating Statement and making connection by using "DriverManager.getConnection"
Now I have a question.
I'm going to create a DBmanager Class that can connect, create tables, execute queries, and execute the code that updates data on tables in a single line.
I thought all the examples would run alone in one method and came from different places, so I could only try a new connection and create a code that would not close. But I have a gut feeling that this will be a problem.
Is there any way I can leave a connection connected at a single connection to send a command, and disconnect it to DB.disconnect()? And I'd appreciate it if you could tell me whether what I'm thinking is right or wrong.
The code below is the code I've written so far.
I am sorry if you find my English difficult to read or understand. I am Using translator, So, my English could not be display as I intended.
import java.sql.*;
import java.util.Properties;
public class DBManager {
/*********INNITIAL DEFINES********/
final static private String HOST="sumewhere.azure.com";//Azure DB URL
final static private String USER="id#somewhere";//root ID
final static private String PW="*****";//Server Password
final static private String DRIVER="org.mariadb.jdbc.Driver";//DB Driver info
private String database="user";
/***************API***************/
void setDB(String databaseinfo){
database=databaseinfo;
}
private void checkDriver() throws Exception
{
try
{
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
}
public void checkOnline(String databaseinfo) throws Exception
{
setDB(databaseinfo);
this.checkDriver();
Connection connection = null;
try
{
String url = String.format("jdbc:mariadb://%s/%s", HOST, database);
// Set connection properties.
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PW);
properties.setProperty("useSSL", "true");
properties.setProperty("verifyServerCertificate", "true");
properties.setProperty("requireSSL", "false");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
void makeCcnnection() throws ClassNotFoundException
{
// Check DB driver Exists
try
{
Class.forName("org.mariadb.jdbc");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
Connection connection = null;
}
public void updateTable(){}
public static void main(String[] args) throws Exception {
DBManager DB = new DBManager();
DB.checkOnline("DB");
}
}
For a studying project it's okay to give a connection from your DB Manager to client code and close it there automatically using try-with-resources construction.
Maybe you will find it possible to check Connection Pool tools and apply it further in your project or use as example (like HikariCP, here is a good introduction).
Read about Java try with resources. I think that this link could be usefull for your problem.
JDBC with try with resources

Connecting to SQL Express DB: connection refused

I have SQL Express 2012 installed on my local machine. I tried connecing with it, by using JDBC 6.2. I downloaded it and declared the dependency(IntelliJ: CTRL, SHIFT, ALT + S --> "Modules" --> "Add" --> "Jars or directories").
Eventually I adjusted the provided code above to my needs, looking like the following:
For some reason, the imported class is not being used at all(it´s greyed out by IntelliJ) - did I made a mistake in terms of dependencies? I´m fairly new to JAVA: to my understanding, setting up the classpath is equal to setting up the depndencies(?).
Moreover I get the error "connection refused". I checked different login credentials as well as the ports(SQL configuration manager as well as netstate) - they are fine. Both, Windows- and SQL authentication didn´t work.
What am I missing?
package com.company;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class Main {
public static void main(String[] args) {
String connectionString = "jdbc:sqlserver://localhost:1433;"
+"database=QMT;"
+"user=superadmin;"
+"password=myPassword.;";
// Declare the JDBC objects.
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}

How to use XAMPP MySQL database with my Java Application?

I have used in the past few months XAMPP with MySQL database(s), which were created and modified with phpMyAdmin on localhost, for my university JavaEE projects. The MySQL database and Apache server are started from the XAMPP Control Panel. Everything went fine.
Now I am developing my own Java Desktop Application using JavaFX/Scene Builder/FXML and I want to use a database to store and load various information processed by the Java Application through JDBC.
The question is, how to start the MySQL database on localhost, without using the XAMPP Control Panel manually, when I finish my Java Application and deploy it as stand alone program and start it just from a single shortcut?
Any way to make the shortcut of the program also start the MySQL database on my PC before/while it starts the Java Application? Or maybe there is a way to do that inside the Java code? Or maybe some other way, that is not known to me?
I am not strictly determined on using only the XAMPP/MySQL/phpMyAdmin setup, it is just already all installed on my PC and I know how to work with it, thus the easiest solution so far. So if there is some better way/database setup for home/small applications, please feel free to suggest some :). I am not sure at all if what I want to do is possible with the XAMPP setup.
Side note: I persist on using localhost DB instead of Serialisation/Deserialisation with Java, because I want the Application to be independent of internet connection and yet have the opportunity to have a ready DB to be transferred to an online DB, if such I decide to do it in the future.
On the root of the Xampp folder you have one mysql_start.bat and one mysql_stop.bat, for start/stop the mysql database included on the Xampp package.
You can use they in another bat you should create to start your Java Desktop application.
ProcessBuilder P1 =new ProcessBuilder("C:\\xampp\\mysql_start.bat");
P1.start();
ProcessBuilder P2 =new ProcessBuilder("C:\\xampp\\APACHE_start.bat");
P2.start();
You can do it like this -
To connect to the Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Statement statement;
//function to connect to the xampp server
public void DatabaseConnect(){
try {
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/javafx","root","");
/*here javafx is the name of the database and root is the username of
your xampp server and the field which is blank is for password.
Because I haven't set the password. I have left it blank*/
statement = conn.createStatement();
System.out.print("Database Connected");
} catch (Exception e) {
System.out.print("Database Not Connected");
}
}
Below given are the various operations you can perform after connecting to the database.
//for inserting data
public void insert(){
try{
String insertquery = "INSERT INTO `tablename`(`field1`, `field2`) VALUES ('value1', 'value2'";
statement.executeUpdate(insertquery);
System.out.print("Inserted");
} catch(Exception e){
System.out.print("Not Inserted");
}
}
//for viewing data
public void view(){
try {
String insertquery = "select * from `table_name` where field = 'value1'";
ResultSet result = statement.executeQuery(insertquery);
if(result.next()){
System.out.println("Value " + result.getString(2));
System.out.println("Value " + result.getString(3));
}
} catch (SQLException ex) {
System.out.println("Problem To Show Data");
}
}
//to update data
public void update(){
try {
String insertquery = "UPDATE `table_name` set `field`='value',`field2`='value2' WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Updated")
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
//to delete data
public void delete(){
try {
String insertquery = "DELETE FROM `table_name` WHERE field = 'value'";
statement.executeUpdate(insertquery);
System.out.println("Deleted");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
Also, don't forget to add the JAR file in your system library. For this example, I have used mysql-connector-java-5.1.46

jdbc connection established but didnt print the result in eclipse console

I am new to this forum....
Iam tring to connect java project created in eclipse with oracle database xe,
I followed the procedures as descrided in the following link
https://www.youtube.com/watch?v=fMp63HsIRbc
but it didnt print the result in the eclipse console but it also didnt throw the exception as well
what should be the reason
this is my code
package dbmsoracle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Jdb {
public static void main(String[] args) {
System.out.println("jen");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
Statement st = con.createStatement();
String sql="select * from muhil";
ResultSet rs =st.executeQuery(sql);
while (rs.next())
{
System.out.println("executing ...");
System.out.println(rs.getInt(1)+" "+rs.getInt(2));
System.out.println("executed");
con.close();
}
}
catch (Exception e)
{
System.out.println("connection failed");
System.out.println(e);
}
}
i have downloaded my jdbc driver
Oracle Database 11g Release 2 (11.2.0.4) JDBC Drivers
ojdbc6.jar
Certified with JDK 8, JDK 7 and JDK 6: ......
and iam using jdk 8
Firstly check that your connection is establishing with oracle database or not. Here is the connection code try this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","system","murali123");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I have the same problem. The problem is your code doesn't catch(SQLException e). Because just catch(Exception e) will not make the exception of sql shown in the console. After doing this, you will probably find the Exception is "No suitable driver found for jdbc".
Then, either you can download the mysql-connector-java and add it to your lib, or if your project is Maven, you can just add dependency in your pom file.
After you used Sql+ for entering database, commit the table. Enter 'commit'(without quotes) on the terminal or either close your Sql+ terminal. In your case, you must have closed the terminal after you changed your id from 24, 253 to 1, 2. That is why it ran properly. Got nothing to do with id starting from 1
first of all go and check if your table has any data or not. It seems you just created this table 'muhil' before writing the above code. i'm pretty sure You must have entered some data as well in your new table. Just make sure you have Committed your transaction in the MYSQL Workbench. Just commit it and try to run your code in eclipse again.

Categories