Iam tryig to connect to a Postgres Database. Iam really new to that and have read a post in the forum. But I didn't manage it.
public void connect() {
//Connection con = null;
try {
Class.forName("org.postgresql.Driver");
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);
//String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
//Connection conn = DriverManager.getConnection(url);
System.out.println("Erfolgreich verbunden!");
}
catch (Exception e){
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
}
EDIT:
I updated my Code.
The database is deployed to heroku.
It throws the error:
java.sql.SQLException: No suitable driver found for jdbc:postgres://vuqmbekwlgohkw:******
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:189)
at com.company.Database.connect(Database.java:20) p
at com.company.Main.start(Main.java:16)
at com.company.Main.main(Main.java:25)
java.sql.SQLException: No suitable driver found for jdbc:postgres://vuqmbekwlgohkw:***************
I believe that your problem is that your connection URL is malformed.
When DriverManager.getConnection throws SQLException, the message includes the exact url value passed to the function. In your case, that looks like jdbc:postgres://vuqmbekwlgohkw:******.
But obviously that is not the URL you are using. You have replaced part of the URL with asterisks. That suggests that you think the format of the URL is:
jdbc:postgres://username:password#host:port/dbname
which seems to be what Heroku provides in the DATABASE_URL environment variable. You are using asterisks to prevent us from seeing the password.
However, it looks like the PostgreSQL JDBC driver does not accept URLs in this format. When I tried, I also got the "No suitable driver" error. According to the documentation, the format of the URL is:
jdbc:postgres://host:port/database
Some parts are optional, but the driver does not appear to support putting the user name or password in the URL.
I was able to connect to an AWS PostgreSQL instance by using the URL format described in the documentation and using the connection properties to set the user name and password.
You said you are new so I'm gonna start with the painfully obvious, do you have the driver on your classpath?
it's a jar you add to your project that you can download from https://jdbc.postgresql.org/
Otherwise I have an example of the url that worked for me, except I was not exactly using jdbc, it was a spring-boot project:
jdbc:postgresql://ec2-174-99-88-88.compute-1.amazonaws.com:5432/asdfasdfsadf?sslmode=require
There is no port number in your commented URL and not all parameters might be supported, like Willis pointed out.
Related
I have been trying to connect to this Oracle database with JDBC thin driver with the following syntax:
var URL = "jdbc:oracle:thin:#//16.161.286.56:1522/Service_Name";
var USER = "user";
var PASS = "password";
var conn = Jdbc.getConnection(URL, USER, PASS);
I keep on having the same response when I execute this:
We're sorry, a server error occurred. Please wait a bit and try again. [87a99af]
Would anyone have an idea of what I am doing wrong ?
Also, when I change the IP address to its 'string version':
var URL = "jdbc:oracle:thin:#//mydomain.com:1522/Service_Name";
Then I get the error response:
Failed to establish a database connection. Check connection string, username and password.
Which does not make sense to me as both expressions are supposed to be equivalent ...
The actual format of Oracle JDBC connection using service name is:
#//host_name:port_number/service_name
Make sure that is service name is ok.
You can try with TNSNameListener
jdbc:oracle:thin:#(description=(address=(host=<HOSTADDRESS>)(protocol=tcp)(port=<PORT>))(connect_data=(service_name=<SERVICENAME>)(server=<SHARED>)))
The TNSNameListener file location:
<ORACLE_HOME>\network\admin\tnsnames.ora
example: /home/oracle/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora
I am not sure which class is that Jdbc is. Take a look at the JDBCUrlSample.java and DataSourceSample.java
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.
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);
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);
....
I am working on a dynamic webapp on eclipse and is trying to access a remote MySQL database. I made sure that all the information is correct. However I can't seem to connect to it. Here's my getConnection method:
public static Connection getConnection() throws SQLException {
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://50.56.81.42:3306/GUEST_BOOK";
String user = "username";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
System.out.println("CONNECTED");
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(InstantiationException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
return conn;
}
I am trying to see what the error is but because this is a web app, I can't see that system.out.println anywhere, so it's kind of hard for me to debug with this. Any suggestions on how to debug?
Is your MySQL server accessible from out of the server? I am asking because it is possible to disable external connection for MySQL server, more info is here.
Your credentials are OK (at least its format).
Otherwise, you create Class.forName("com.mysql.jdbc.Driver").newInstance(); but you don't assign it to conn variable.
In web applications, System.out prints to the server's logs file. If you are using tomcat, see logs directory inside tomcat's base directory.
If you are still struggling to see the System out in logs, try to test the class from standalone java class, you will clearly see what the problem is.