I know this is very similar to questions already answered, but there is a slight variation.
I have a list of connections in my production connection setup. The process is to start with the first and keep trying till I get a connection. I would like to be able to run a task that used this same list as its input, but did just enough to show which of the connections will be used by the application. To avoid our security team getting all upset, this would have to be done without the username/password.
Is it possible?
Below answer may be helpful to you. getErrorCode() method in SQLException returns 1017 value on authentication failure. So you can iterate through list of connections and invoke validateConnection.
I'm using dummy username and password here (I don't see any other option)
Replace host, port and SID values.
public static void main(String[] args) {
String connString = "jdbc:oracle:thin:#host:port:SID";
System.out.println(validateConnection(connString));
}
public static boolean validateConnection(String connString) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(connString, "x", "y");
} catch (SQLException sqle) {
if (sqle.getErrorCode() == 1017)
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Related
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
Heading ##I have problem with my java application with database in mySQL and swing GUI.
When I've used localhost everything worked properly. But now I would like to share project with my friend and we decided to use server hosting.
And here is a problem:
Now application works very slow, after pressing a button I have to wait a few seconds for the program to respond. Also the connection is lost from time to time. I have no idea where can I find reason for the problem... Do somebody now what is the reason of this problem?
private static Connection connection = null;
Boolean error = false;
private static String jdbcURL = "jdbc:mysql://host_name:3306/db_name";
private static String user = "user";
private static String password = "password";
MakeConnection(Connection connection) throws SQLException{
this.connection = connection;
try {
getConnection();
System.out.print("Connected to the data base in MakeConnection");
}
catch(Exception e) {
error = true;
System.out.print("Error in connection in MakeConnection consturctor" + e.getMessage());
}
finally{
if(connection!=null) connection.close();
if(error) System.out.print("Problem with connection");
else System.out.print("Program finished");
}
}
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL,user,password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
Also sometimes application shows this error:
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I don't see any problem in your code. The problem is probably with your server hosting. You should check the country of the host provider and measure the time required to send a request to the server. Also you should use logger instead of System.out.println so you can examine required time for actions like db access, application logic and find a bottleneck.
I have a problem when running my code in NetBeans in order to see if mySQL is connected. This is the code:
public static void main(String[] args) {
Connection connect = null;
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}
}
}
when I run it prints out "RIP". When I debugged it line by line, it went from the "connect = DriverManager.getConnection..." to "System.out.println("RIP"), and when I look at the "Exception e" it says "e = (java.sql.SQLNonTransientConnectionException) java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=TRUE'."
Now, why is that?????
I think you need to add
Class.forName("com.mysql.jdbc.Driver"); .
Also, make sure everything in Connection conn = DriverManager.getConnection (String url, String user, String password); are set correctly.
From the url format in your code, it's like you are trying to get direct connect to specific table tUsers in your database. And I dont think that would work. Correct me if I'm wrong whether it's literally your database name or not.
Because the basic url format i know, should be like jdbc:mysql://localhost:3306/yourDBname .
If you already set the url correctly as is written in your post, then the code is
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}}}
Hope that could do the work.
I'm still working on the same problem mention here. It seems to work fine especially after creating an AbstractModel class shown below:
public abstract class AbstractModel {
protected static Connection myConnection = SingletonConnection.instance().establishConnection();
protected static Statement stmt;
protected static ResultSet rs;
protected boolean loginCheck; // if userId and userLoginHistoryId are valid - true, else false
protected boolean userLoggedIn; // if user is already logged in - true, else false
public AbstractModel (int userId, Long userLoginHistoryId){
createConnection(); // establish connection
loginCheck = false;
userLoggedIn = false;
if (userId == 0 && userLoginHistoryId == 0){ // special case for login
loginCheck = true; // 0, 0, false, false
userLoggedIn = false; // set loginCheck to true, userLogged in to false
} else {
userLoggedIn = true;
try{
String query = "select \"user_login_session_check\"(" + userId + ", " + userLoginHistoryId + ");";
System.out.println("query: " + query);
stmt = myConnection.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()){
loginCheck = rs.getBoolean(1);
}
} catch (SQLException e){
System.out.println("SQL Exception: ");
e.printStackTrace();
}
}
}
// close connection
public void closeConnection(){
try{
myConnection.close();
} catch (SQLException e){
System.out.println("SQL Exception: ");
e.printStackTrace();
}
}
// establish connection
public void createConnection(){
myConnection = SingletonConnection.instance().establishConnection();
}
// login session check
public boolean expiredLoginCheck (){
if (loginCheck == false && userLoggedIn == true){
closeConnection();
return false;
} else {
return true;
}
}
}
I've already posted the stored procedures and Singleton Pattern implementation in the link to the earlier question above.
I'm under the impression that I don't need to close the connection to the database after each single data transaction, as it would just slow the application. I'm looking at about 30 users for this system I'm building, so performance and usability is important.
Is it correct to prolong the connection for at least 3-4 data transactions? Eg. Validation checks to user inputs for some form, or, something similar to google's auto-suggest ... These are all separate stored function calls based on user input. Can I use one connection instance, instead of connecting and disconnecting after each data transaction? Which is more efficient?
If my assumptions are correct (more efficient to use one connection instance) then opening and closing of the connection should be handled in the controller, which is why I created the createConnection() and closeConnection() methods.
Thanks.
Your code should never depend on the fact, that your application is currently the only client to the database or that you have only 30 users. So you should handle database connections like files, sockets and all other kinds of scarce resources that you may run ouf of.
Thus you should always clean up after yourself. No matter what you do. Open connection, do your stuff (one or SQL statements) and close connection. Always!
In your code you create your connection and save it into a static variable - this connection will last as long as your AbstractModel class lives, probably forever - this is bad. As with all similar cases put you code inside try/finally to make sure the connection gets always closed.
I have seen application servers running ouf of connections because of web applications not closing connections. Or because they closed at logout and somebody said "we will never have more then that much users at the same time" but it just scaled a little to high.
Now as you have your code running and closing the connections properly add connection pooling, like zaske said. This will remedy the performance problem of opening/closing database connection, which truely is costly. On the logical layer (your application) you doesn't want to know when to open/close physical connection, the db layer (db pool) will handle it for you.
Then you can even go and set up a single connection for your whole session model, which is also supported by DBCP - this is no danger, since you can reconfigure the pool afterwards if you need without touching your client code.
Like Tomasz said, you should never ever depend on the fact that your application will be used by a small number of clients. The fact that the driver will timeout after a certain amount of time does not guarantee you that you will have enough available connections. Picture this: a lot of databases come pre-configured with a maximum number of connections set to (say) 15 and a timeout of (let's say) 10-15 minutes. If you have 30 clients and each does an operation, somewhere around half-way you'll be stuck short on connections.
You should handle connections, files, streams and other resources the following way:
public void doSomething()
{
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
final String sql = "SELECT ....");
try
{
connection = getConnection();
stmt = connection.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next())
{
// Do something here...
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
closeResultSet(rs);
closeStatement(stmt);
closeConnection(connection);
}
}
The try/catch/finally guarantees you that the connection will get closed no matter the outcome. If there is some sort of failure, the finally block will still close the connection, just like it would do, if things were okay.
Similarly, with file and streams you need to do the same thing. Initialize the respective object as null outside your try/catch/finally, then follow the approach above.
This misconception makes a lot of Java applications misbehave under Windows, where people don't close files (streams to files, etc) and these files become locked, forcing you to either kill the JVM, or even restart your machine.
You can also use a connection pool such as for example Apache's DBCP, but even then you should take care of closing your resources, despite the fact that internally, the different connection pool implementations do not necessarily close the connections.
You'are right that you don't need to close the connection after each call.
Bare in mind that that modern database implement internal connection pools, but your application still need to connect and retrieve a connection object, and this is what it does now.
You should consider using a database connection pool - there are various Java frameworks to provide you such a solution, and they will define (you will be able to configure of course) when a database connection pool is closed.
In general - you should ask yourself whether your database serves only your application, or does it serve other application as well - if it does not serve other application as well, you might be able to be more "greedy" and keep connections open for a longer time.
I would also recommend that your application will create on start a fixed number of connections (define it in your configuration with a value of "Minimum connections number") and you will let it grow if needed to a maximum connection numbers.
As I previously mentioned - the ideas are suggest are implemented already by all kinds of frameworks, for example - the DBCP project of Apache.
Here is the Singleton Pattern which I initialize the myConenction field in all my Models to:
public class DatabaseConnection {
private static final String uname = "*******";
private static final String pword = "*******";
private static final String url = "*******************************";
Connection connection;
// load jdbc driver
public DatabaseConnection(){
try{
Class.forName("org.postgresql.Driver");
establishConnection();
} catch (ClassNotFoundException ce) {
System.out.println("Could not load jdbc Driver: ");
ce.printStackTrace();
}
}
public Connection establishConnection() {
// TODO Auto-generated method stub
try{
connection = DriverManager.getConnection(url, uname, pword);
} catch (SQLException e){
System.out.println("Could not connect to database: ");
e.printStackTrace();
}
return connection;
}
}
public class SingletonConnection {
private static DatabaseConnection con;
public SingletonConnection(){}
public static DatabaseConnection instance(){
assert con == null;
con = new DatabaseConnection();
return con;
}
}
Of course each and every connection to the database from the app goes through a Model.
hey all, I'm new to Java and was wondering if I define a method to return a database object
like
import java.sql.*;
public class DbConn {
public Connection getConn() {
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
if(System.getenv("MY_ENVIRONMENT") == "development") {
String hostname = "localhost";
String username = "root";
String password = "root";
}
conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
return conn;
} catch(Exception e) {
throw new Exception(e.getMessage());
}
}
}
if the connection fails when I try to create it what should I return? eclipse is telling me I have to return a Connection object but if it fails I'm not sure what to do.
thanks!
UPDATED CODE TO LET EXCEPTION BUBBLE:
public class DbConn {
public Connection getConn() throws SQLException {
Connection conn;
String hostname = "localhost";
String username = "root";
String password = "root";
Class.forName("com.mysql.jdbc.Driver").newInstance();
if(System.getenv("MY_ENVIRONMENT") != "development") {
hostname = "localhost";
username = "produser";
password = "prodpass";
}
conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
return conn;
}
}
If an exception is thrown, there is no normal value returned from the method. Usually the compiler is able to detect this, so it does not even pester you with "return required" style warnings/errors. Sometimes, when it is not able to do so, you need to give an "alibi" return statement, which will in fact never get executed.
Redefining your method like this
public Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
if(System.getenv("MY_ENVIRONMENT") == "development") {
String hostname = "localhost";
String username = "root";
String password = "root";
}
conn = DriverManager.getConnection("jdbc:mysql:///mydb", username, password);
} catch(Exception e) {
// handle the exception in a meaningful way - do not just rethrow it!
}
return conn;
}
will satisfy Eclipse :-)
Update: As others have pointed out, re-throwing an exception in a catch block the way you did is not a good idea. The only situation when it is a decent solution is if you need to convert between different exception types. E.g. a method called throws an exception type which you can not or do not want to propagate upwards (e.g. because it belongs to a proprietary library or framework and you want to isolate the rest of your code from it).
Even then, the proper way to rethrow an exception is to pass the original exception into the new one's constructor (standard Java exceptions and most framework specific exceptions allow this). This way the stack trace and any other information within the original exception is retained. It is also a good idea to log the error before rethrowing. E.g.
public void doSomething() throws MyException {
try {
// code which may throw HibernateException
} catch (HibernateException e) {
logger.log("Caught HibernateException", e);
throw new MyException("Caught HibernateException", e);
}
}
You should just eliminate your entire try/catch block and allow exceptions to propagate, with an appropriate exception declaration. This will eliminate the error that Eclipse is reporting, plus right now your code is doing something very bad: by catching and re-throwing all exceptions, you're destroying the original stack trace and hiding other information contained in the original exception object.
Plus, what is the purpose of the line Class.forName("com.mysql.jdbc.Driver").newInstance();? You're creating a new mysql Driver object through reflection (why?) but you're not doing anything with it (why?).
Never, ever, ever use a generic exception like that. If you don't have a ready made exception (in this case, an SQLException), make your own exception type and throw it. Every time I encounter something that declares that it "throws Exception", and it turns out that it does so because something it calls declares "throws Exception", and so on down the line, I want to strangle the idiot who started that chain of declarations.
This is exactly the situation where you should let the exception propagate up the call stack (declaring the method as throws SQLException or wrapping it in a application-specific exception) so that you can catch and handle it at a higher level.
That's the whole point of exceptions: you can choose where to catch them.
I'm sorry, but you shouldn't be writing code like this, even if you're new to Java.
If you must write such a thing, I'd make it more like this:
public class DatabaseUtils
{
public static Connection getConnection(String driver, String url, String username, String password) throws SQLException
{
Class.forName(driver).newInstance();
return DriverManager.getConnection(url, username, password);
}
}
And you should also be aware that connection pools are the true way to go for anything other than a simple, single threaded application.
Try this one
public ActionForward Login(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
MigForm migForm = (MigForm) form;// TODO Auto-generated method stub
Connection con = null;
Statement st = null;
ResultSet rs = null;
String uname=migForm.getUname();
String pwd=migForm.getPwd();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","uname","pwd");
if(con.isClosed())
{
return mapping.findForward("success");
}
//st=con.createStatement();
}catch(Exception err){
System.out.println(err.getMessage());
}
return mapping.findForward("failure");
}