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.
Related
I am unable to connect a PostgreSQL db on Android. Using JDBC is for development purpose only and will change to proper web service.
I have implemented the PostgreSQL driver in build.gradle as "implementation 'org.postgresql:postgresql:42.2.18.jre7"
My PostgreSQL database server is listening to port: 5433
My computer IP in my network is 192.168.1.103
And the user name and password is set correct
The connection:
Connection con = null;
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/* Register jdbc driver class. */
Class.forName("org.postgresql.Driver");
/* Create connection url. */
String postgresConnUrl = "jdbc:postgresql://192.168.1.103:5433/lmsdb";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","xxxxxxx");
props.setProperty("ssl","false");
/* Get the Connection object. */
con = DriverManager.getConnection(postgresConnUrl, props);
}catch(Exception ex)
{
ex.printStackTrace();
}finally
{
return con ;
}
When I change the IP in "postgresConnUrl" to 127.0.0.1 which is set in pg_hba, I get the error
org.postgresql.util.PSQLException: Connection refused. Check that the
hostname and port are correct and that the postmaster is accepting
TCP/IP connections
And when I use my computer's IP address as shown in the connection code above, the connection con = DriverManager.getConnection(postgresConnUrl, props); is returning null. The log shows no exception or errors, but the con is null and I am unable to trace the problem. Any directions to the problem would be helpful.
DriverManager.getConnection(...) cannot return null. Unless there is a severe bug in the implementation, it always returns a non-null connection or throws a SQLException (or RuntimeException or Error as thrown by drivers).
The PostgreSQL driver is likely causing an Error to be thrown (e.g. a NoClassDefFoundError, because the PostgreSQL JDBC driver uses Java features or classes not present on Android). This is hidden by the fact that your finally block will unconditionally return con, and you only catch and log instances of Exception, but not Error. See also Adding return in finally hides the exception
Remove your catch and finally block and let any exception or other Throwable bubble up to the caller, instead of replacing an explicit exception or error with a hidden error (returning null), alternatively have the catch block wrap the exception in a custom exception and throw that custom exception.
I recommend you don't use JDBC on Android. Most recent JDBC drivers are using Java features or classes not present on Android, which can cause all kinds of issues. You mention you're doing this for development purposes, but I would suggest that creating or mocking your REST API and using that from the start will save you a lot of headaches and unnecessary development work.
I tried using older version of JDBC and I was able to connect. The newer version of JDBC does not seem to be compatible with Android and result in error as you posted. But, still I can see many people are using JDBC as it is easy although Rest API is better option but requires additional skills.
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.
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);
....
Here's my code:
import java.sql.*;
public class DBConnector {
private static Connection conn;
public static void connectToDB()
{
//load the driver
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("Driver successfully loaded");
}
catch (ClassNotFoundException c)
{
System.out.println ("Unable to load database driver");
}
//connect to the database
try
{
String filename = "TopYouTubeVideos.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database += filename.trim () + ";DriverID=22;READONLY=true}";
conn = DriverManager.getConnection (database, "", "");
System.out.println ("Connection database successfully established");
}
catch (Exception e)
{
System.out.println ("Unable to connect to the database");
}
}
The output is:
Driver successfully loaded
Unable to connect to the database
This has worked on a different computer than mine, connecting to the database through exactly the same code... does anyone have any idea why?
Thanks in advance :)
EDIT: I'm running Access 2007, Windows 7 64bit
By checking for the error, I get: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
From a little bit of research it seems this is a problem with my 'data source name'. I put my database file in the project folder, and the name is correct. Why is it not finding it?
EDIT: No, the database was the same on both computers. In the same folder as well.
EDIT: I think I may need to create a system dsm. Following the instructions on the internet dosent work though, because I dont have the same files as them..
EDIT: I've tried to install that but it hasn't made a difference. My version of access is 64 bit alongside my version of netbeans..
Try installing a database engine + JVM that are both running in the same archeticture (i.e. 32bit), otherwise, you would receive a mismatch exception. I assume your JVM is 64bit but your database engine is not, so try installing a 64bit engine from the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=13255