I am trying to connect to a database in Mariadb through a simple java application but the connection is told to be unsuccessful and an Exception is thrown. I have done the similar connection using mysql and it was working correctly. The problem is maybe with the driver here.
try{
Class.forName("org.mariadb.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/project", "root", "");
Statement statement = connection.createStatement();
String uname="xyz",pass="abc";
statement.executeUpdate("insert into user values('"+uname+"','"+pass+"')");}//end of try block
I looked up the internet for the help and came by that driver class provided by the MariaDB Client Library for Java Applications is not com.mysql.jdbc.Driver but org.mariadb.jdbc.Driver! I changed it accordingly but it seems the problem is with the very first line inside the try block. The driver is not loading at all.
Also, I have added the mysql jar file to the libraries of my java application as in the screen-shot below. Please help me through this.
It appears that you are trying to use jdbc:mariadb://... to establish a connection to a MariaDB server instance using the MySQL JDBC Driver. That probably won't work because the MySQL JDBC Driver would use jdbc:mysql://..., regardless of whether it is connecting to a MySQL server or a MariaDB server. That is, the connection string must match the driver that is being used (rather than the database server being accessed).
The MySQL and MariaDB drivers are supposed to be somewhat interchangeable, but it only seems prudent to use the MariaDB connector when accessing a MariaDB server. For what it's worth, the combination of mariadb-java-client-1.1.7.jar
and
Connection con = DriverManager.getConnection(
"jdbc:mariadb://localhost/project",
"root",
"whatever");
worked for me. I downloaded the MariaDB Client Library for Java from here:
https://downloads.mariadb.org/client-java/1.1.7/
which I arrived at via
https://downloads.mariadb.org/
Additional notes:
There is no need for a Class.forName() statement in your Java code.
The default configuration for MariaDB under Mageia may include the skip-networking directive in /etc/my.cnf. You will need to remove (or comment out) that directive if you want to connect to the database via JDBC because JDBC connections always look like "network" connections to MySQL/MariaDB, even if they are connections from localhost. (You may need to tweak the bind-address value to something like 0.0.0.0 as well.)
An additional note:
Exploring the MariaDB JDBC driver, I found this inside the url parsing file:
Project: https://github.com/MariaDB/mariadb-connector-j.git
File: src/main/java/org/mariadb/jdbc/UrlParser.java
public static UrlParser parse(final String url, Properties prop) throws SQLException {
....
if (url.startsWith("jdbc:mysql:")) {
UrlParser urlParser = new UrlParser();
parseInternal(urlParser, url, prop);
return urlParser;
} else {
if (url.startsWith("jdbc:mariadb:")) {
UrlParser urlParser = new UrlParser();
parseInternal(urlParser, "jdbc:mysql:" + url.substring(13), prop);
return urlParser;
}
}
As you can see, the string "jdbc:mariadb:" is always replaced with "jdbc:mysql:" internally. So when it comes to the MariaDB driver, whether it is :mariadb: or :mysql: it always gets parsed as "jdbc:mysql:".
No difference.
if (url.startsWith("jdbc:mariadb:")) {
....
parseInternal(urlParser, "jdbc:mysql:" + url.substring(13), prop);
....
Related
Dear StackOverFlowers,
I was trying event-driven LISTENER/NOTIFY on Postgres 9.6 (Windows 10).
I followed PGJDBC example given by Steve Taylor at https://www.openmakesoftware.com/postgresql-listen-notify-events-example/.
I started by downloading pgjdbc-ng-0.7-complete.jar and have put that in my CLASSPATH replacing standard JDBC driver.
When I am trying to connect to Postgres database using pgjdbc driver, I am getting an error:
connection received: host=127.0.0.1 port=50325
connection authorized: user=postgres database=scott
could not receive data from client: An existing connection was forcibly closed by the remote host.
Here are my system variables:
DBHost: localhost
DBName: scott
DBPort: 5432
DBUserName: postgres
DBPassword: postgres
I am not getting past the first hurdle, rest looks like Mount Everest. Please help me. Should you be needing the code, I am following Steve's code ditto.
Further to Joseph Larson's answer, the database is always running. I have connected to Postgres database from PGADMIN and Java successfully. I think issue is with the connect string. From Java when I am using standard JDBC which is provided by Postgres I am using URL like jdbc:postgresql://localhost:5432/dbname but PGJDBC suggests a different connect string like JDBC:PGSQL://localhost:5432/dbname. I tried to connect with that string (forcibly), it did not work. There is no method in PGJDBC PGDataSource for providing URL directly. I had to go through:
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
And what URL it is sending to Database I am not able to figure out. Please suggest me a connect string and this problem is solved.
thanks
Thanks very much for asking me to post error messages:
Exception in thread "main" java.lang.NullPointerException
at com.impossibl.postgres.system.BasicContext.loadLocale(BasicContext.java:294)
at com.impossibl.postgres.system.BasicContext.init(BasicContext.java:273)
at com.impossibl.postgres.jdbc.PGConnectionImpl.init(PGConnectionImpl.java:251)
at com.impossibl.postgres.jdbc.ConnectionUtil.createConnection(ConnectionUtil.java:182)
at com.impossibl.postgres.jdbc.AbstractDataSource.createConnection(AbstractDataSource.java:723)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:66)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:58)
at PGListenNotify.<init>(PGListenNotify.java:26)
at PGListenNotify.main(PGListenNotify.java:37)
Here is source code:
import java.sql.SQLException;
import java.sql.Statement;
import com.impossibl.postgres.api.jdbc.PGConnection;
import com.impossibl.postgres.jdbc.PGDataSource;
public class PGListenNotify
{
PGConnection connection;
public PGListenNotify()
{
String DBHost = System.getenv("DBHost");
String DBName = System.getenv("DBName");
String DBUserName = System.getenv("DBUserName");
String DBPassword = System.getenv("DBPassword");
try
{
PGDataSource dataSource = new PGDataSource();
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
connection = (PGConnection) dataSource.getConnection();
Statement statement = connection.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
PGListenNotify ln = new PGListenNotify();
}
}
This looks like the Windows locale bug in pgjbdc-ng. It has been addressed, try the latest version 0.8.1.
The latest releases have detailed documentation related to asynchronous notifications here.
If it still fails to execute on your Windows system, please create an issue here.
Did you actually start a database server? I didn't know PostgreSQL server could run on Windows, but I've never tried.
I would simplify your problem a little. I know nothing about psql on Windows, but on Mac, I would start the server and then use the psql command (it's part of PostgreSQL) to ensure the server was up and running.
If you're to connecting, then the problems can be:
-There is no server at all
-The server isn't running on the port you're attempting
-The server isn't listening for connections on host 127.0.0.1 but could be listening on the actual IP address of your machine
-I'm not sure about that particular error, but username, password, or database may not exist.
I'd use psql to figure out which of those possible reasons is the real problem. That isolates out your program as being part of the problem, and it becomes entirely one of managing your database server.
I know this has been asked a hundred times and I think I have read all the posts and tried every variation of the solutions. I'm using NetBeans and new to it. I'm sure I'm just missing some small step because it seems like its just not seeing the driver that I added to the library. This is the first time I have tried to connect to a database so please be gentle.
try
{
String host = "jdbc:sqlserver://Server:1433;Database";
String uName = "User";
String uPass = "Password";
Connection con = DriverManager.getConnection(host,uName,uPass);
System.out.println("Your are connected to SQLServer 2014");
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
You forgot to register the jdbc driver class.
Call
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
before calling Connection con = DriverManager.getConnection(host,uName,uPass);.
It will resolve the issue.
UPDATE
In documentation for new jdbc drivers it is declared that this step is not necessary. But in practical work, I have found that this step is required even for new drivers, otherwise you will get "No suitable driver found" error. This error occurs sometimes, for example it does not occur when you are making and running a console jar-application, but occurs when you have created and deployed a web-application.
So, I advise to register the jdbc driver class before getting the database connection via DriverManager.getConnection() call.
In java I am trying to connect with Sybase database through java program as shown below
public static void connect() {
SybDriver sybDriver = null;
Connection conn;
try {
sybDriver = (SybDriver) Class.forName(
// "com.sybase.jdbc3.jdbc.SybDriver").newInstance();
"com.sybase.jdbc2.jdbc.SybDriver").newInstance();
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url, username, password);
boolean isTrue = conn.isValid(3);
System.out.println(isTrue);
But i am getting the below exception
Driver Loaded
Exception in thread "main" java.lang.AbstractMethodError: com.sybase.jdbc2.jdbc.SybConnection.isValid(I)Z
at connectionTry.connect(connectionTry.java:97)
at connectionTry.main(connectionTry.java:23)
I have done analysis in google what i have to came up to know jconnn.jar is missing as the issue is the method isValid(I)Z is not there in jconn2.jar is not there please advise how to overcome from this error please.
The driver you are using is - based on the class name in the stacktrace - a JDBC 2 driver. The isValid method was added in Java 6 (or: JDBC 4), so you can't use it with a driver that doesn't implement it.
You either need to upgrade to a newer driver: contact Sybase for that, or simply not call the isValid method. In the code you show there is no reason to call it: you just created the connection, of course it is valid. This method is intended to check the validity of long-living connections (eg in the context of a connection pool).
AbstractMethodError is thrown when the implementation class doesn't comply to the signature defined in the abstract class. Use a compatible version of the implementation or alternatively avoid the methods that conflict.
Ideally latest version of drivers must be having matching implementations or you will have to contact sybase to fix that.
I am trying to connect to one of my MySql Databases through a System DSN I set up. The DSN is set up correctly with my SSL certs, username, password, port, and the databases populate the DSN database drop down and the "Test" connection passes. I can't seem to get a connection in Java. I have spent 2 days looking through some examples on Stack but they all refer to an Access database and using JDBC-ODBC bridge which is no longer available in Java 8. I tried using UCanAccess with Jackcess but I have gotten no where. The code below is what I have been tinkering with the last few hours. I normally connect to MySql databases with PHP and receive result in JSON or directly with JDBC driver but for this project neither are really an option. Any ideas. I appreciate the help.
//String username = "<username>";
//String password = "<password>";
//String database = "<database_name>";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//Connect to cllients MySql Database
Connection conn = DriverManager.getConnection("jdbc:ucanaccess:" + database);
//Call VerifyLabel(<MAC>,<MODEL>); Call provided client
CallableStatement cStmt = conn.prepareCall("{CALL verify(?, ?)}");
//MAC
cStmt.setString(1, "mac address");
//model
cStmt.setString(2, "model");
cStmt.execute();
//Getting results from "Status" column
ResultSet rs1 = cStmt.getResultSet();
//Iterate results and print.
while (rs1.next()) {
System.out.println(rs1.getString("Status"));
}
//Close connection conn
rs1.close();
} catch (SQLException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
}
Using MySql Driver:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:"+ database);
also tried:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ database);
Error for MySql Driver:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
1) DSN is most commonly assocatiated with ODBC (and often with MS-Access). Hence all the links. ODBC is NOT required for a DSN.
2) Do NOT use Ucanaccess. Use J/Connector for mySQL.
3) Make sure you can communicate with mySQL from the command line. Then focus on getting a small "hello world" JDBC app to connect. Your second and third examples look OK. Be sure to check the mySQL logs for any warnings/errors.
Well, after an entire day of trying to get this to work and sleeping on it for a couple hours I finally got it to work. UCanAccess and mysql-connector did not work. The easiest thing since no other method of connecting to this clients database was acceptable was to push this application in Java 7 rather than 8. This allowed me to Coo=nnect to my DSN with no problems. I understand that this method is not the best solution but it is what is working flawlessly and efficiently. Also, instead of using some rigged up 3rd party libs and jars, I am able to use Connector/J. Thanks everyone for trying to help me. Just incase anyone else runs into this issue, this is how I made it work.
Develope app in Java 7 - not 8.
Set Up System DSN
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//You do not need to provide username or password if it is setup in DSN
Connection conn = DriverManager.getConnection("jdbc:odbc:"+ database);
Background: Working on an application to be run on an Apache server hosted by Network Solutions. Friend/Customer insisted on using an Access Database instead of SQL database.
Current Problem: Wrote a Java test program to make sure I can connect to the database before I dive head first into writing the whole backend. When I run this code on the JVM of the apache server the final product will be hosted:
import java.sql.*;
import java.io.*;
public class test {
public static void main(String[] args) {
try {
Class driverClass = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
DriverManager.registerDriver((Driver) driverClass.newInstance());
// set this to a MS Access DB you have on your machine
String filename = new File(".").getCanonicalPath() + "/ITEMS.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim(); // add on to the end
// now we can get the connection from the DriverManager
System.out.println(database);
Connection conn = DriverManager.getConnection( database );
} catch (Exception e) {
System.out.println("Error: " + e.getMessage() + " " + e.getLocalizedMessage());
e.printStackTrace();
}
}
}
I get a null pointer exception on the line Connection conn= DriverManager.getConnection( database)
Here is the stacktrace:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:436)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at test.main(test.java:20)
To write this test I used this as my primary source: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2691&lngWId=2
String strconnect="jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ="
Sring filename="some path";
StringBuilder a =new StringBuilder();
a.append(strconnect);
a.append(filename);
String db = a.toString();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c= DriverManager.getrConnection(db,"","")
Statement stmt = c.createStament();
String query = "some query";
stmt.executeQuery(query);
c.close();
Never get canonical Path, Either Specify the path of the access file or use JFile Explore and get path
also don't forget to close connection
Since you mention apache, I will presume that the server is running Linux or BSD.
In that case, please have a look at the following:
Connecting to access database from linux
Good Linux ODBC drivers for Access are expensive! (US$850 for a single machine!)
There is no default drivers for Access provided on linux, and the JDBC ODBC won't work unless you install one.
Unless there is a very special and overwhelming good reason for using an Access database as the backend to a website on a linux server, tell your friend that this is not technically or even economically coherent.
If you need a lightweight database on the server, use SQLite: it's free, there is good support for connecting to it from Java in linux, there is good tooling (even browser plugins), and you can always convert that database to Access if your friend want to get an Access backup once in a while.
Otherwise, go for PostgreSQL or MySQL like everyone does (generally for a good reason).