IntelliJ - Problem connecting to PostgreSQL - java

I am new to PostgreSQL (I normally use other database engines), and I also do not use Java often.
My Problem is that I get the following exception:
java.sql.SQLException: No suitable driver found for DATABASE_NAME
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
I followed this tutorial: http://www.postgresqltutorial.com/postgresql-jdbc/connecting-to-postgresql-database/ and added postgresql-42.2.5.jar as a library.
The problem is that adding the driver as a library, as can be seen in the screenshot, has no effect.
So my question is: how do I connect to a PostgreSQL database using Java and the latest IntelliJ?
Any help would be appreciated.
UPDATE 1:
UPDATE 2:
Since the code has been requested: I have replaced the original code by a minimal code that will cause the error:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class IngestData
{
protected static String url;
protected static final String user = "user";
protected static final String password = "password";
public static void main(String[] args)
{
Connection connection = null;
url = args[args.length-1];
try
{
connection = DriverManager.getConnection(url, user, password);
System.out.println("SUCCESS");
} catch (SQLException e)
{
System.out.println("ERROR");
e.printStackTrace();
}
}
}
The console output is:
ERROR
java.sql.SQLException: No suitable driver found for http://127.0.0.1:10282/db01617792
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at IngestData.main(IngestData.java:17)
Process finished with exit code 0
Here is the link to the git repository containing the code:
https://github.com/ka6555/StackOverflow-Postgresql-Problem.git
UPDATE 3:
I found the error:
I need to change
protected static String url;
to
protected static String url = "jdbc:postgresql://";
and
url = args[args.length-1];
to
url += args[args.length-1];
While this solves my original problem, the program is now stuck executing the following line:
connection = DriverManager.getConnection(url, user, password);
There is no error but the program will simply run like with an endless loop never going beyond this code line.
UPDATE 4:
I have fixed all problems now.

It seems like you are missing the postgres jar file in your project dependencies.
Open the Project Structure (Ctrl+Alt+Shift+S on Windows)
Select modules / dependencies tab
You should see something like the following:
If the postgres dependency is missing:
Klick on the + sign on the right side of the screenshot
Choose Library/Project Library and your postgres jar file
Your code should now run. Let me know if it helps.
Note: Please provide your minmal working code on GitHub for a quicker response.

The main problem was that I used a command line parameter as the database url without prefixing it with jdbc:postgresql://. Additionally, I had to reinstall postgresql because of some odd behavior I could not figure out the reason for.

This is the message you get when the URL syntax is incorrect.
This is the requirement.

Related

Connect Java to MariaDB in VS Code

I need to connect to my database but I keep getting an error that says "driver not found".
I have added mariadb-java-client-3.0.8.jar jar file and it is still not working.
And this works pretty well on NetBeans, but I need to know how to fix that in VScode IDE. Do you know what I am missing?
import java.sql.Connection;
import java.sql.DriverManager;
public class App {
public static void main(String[] args) throws Exception {
try {
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/cpit305-project", "root", "");
System.out.println("working");
} catch (Exception e) {
System.err.println(e);
}
}
}
The exception:
java.sql.SQLException: No suitable driver found for jdbc:mariadb://localhost:3306/cpit305-project
First make sure your connection string is correct. Then the database name avoids the use of dashes (-).
The same code works fine for me.
Download the connection package here.
I have faced the same problem. I solved it by exporting classpath into my .zshrc file.
Add this to you shell:
export CLASSPATH=/path/mysql-connector-java-ver.jar:$CLASSPATH

Java JDBC Driver stops working after initial execution [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
I am currently making a backend reporting system (for a voting system assignment) using Java on VS Code, I am connecting to a MySQL database using the JDBC library in order to do calculations and stats and so on. So what happens is that once I create a project file and include the mysql-connector-java-8.0.25.jar in the referenced libraries, I can connect to the DB and retrieve data from the tables just fine, but after a few executions I no longer get output and it shows me the error "java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver".
Can anyone tell me why this is happening and how to fix this? There are no changes that I know of taking place in the Environment Variables (at least from what I can see in Windows path list) unless something is being overwritten somewhere or that it's a bug of some sort. Any advice would be greatly helpful, I've been unable to figure this out all day
This is what my ReportSystem.java looks like...
import java.sql.*;
public class ReportSystem
{
public static void main(String[] args)
{
//Test driver connection/registration
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ElectionDB","<username>","<password>");
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM ElectionDB.Votes");
int typeColumn = 1;
int districtColumn = 2;
//Output results line by line
while(result.next())
{
System.out.println(result.getString(typeColumn));
System.out.println(result.getString(districtColumn));
}
//Remember to close the connection
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
My file structure as in the directory is as follows:
ReportSystem
>src > ReportSystem.java
> ReportSystem.class
>lib
>.vscode > settings.json
The JRE system library used is: [jdk-16.0.1]
The Referenced Libraries contains: [mysql-connector-java-8.0.25.jar]
Screenshot for context Project Setup in VS Code
I'm able to get result after running code 20 times continuously by clicking the run button. The only difference is the JDBC connection string, which is copied directly by right clicking the MYSQL connection:
So in my project, the connection string is like:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=username","<username>","<password>");
OR
You could try
String url="jdbc:mysql://localhost:3306/ElectionDB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
For your reference, OS Infomation:
MySQL: 8.0 // mysql-connector-java-8.0.25.jar
VSCode: 1.56.2 //
java.home: JDK16 // Debugger for Java: 0.33.1

No main class found

Language: Java
Program: Connecting to a database
Question: I'm trying to connect the sqlite database by following TutorialsPoint tutorial but I keep getting the main class not found error.
Implementation: My code is below followed by my terminal commands and folder structure screenshot. But basically all my files are located in one folder including the sqlite jar file.
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection c = null;
try{
Class.forName("com.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch(Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully!");
}
}
Terminal Commands
javac Test.java
java -classpath ".;sqlite-jdbc-3.23.1.jar" Test
Your problem was that you're explicitly trying to load the class com.sqlite.JDBC, whereas the driver class name must've changed somewhere along the way.
JDBC Type 4 drivers have added cleverness which allows you to specify only the connection URL, and the driver loads itself based on the beginning (i.e. jdbc:sqlite). No need to wonder what was the driver class's name.
Rant unrelated to the issue at hand:
Unfortunately people read old tutorials written by less than experts, so we constantly see Class.forName() being used, as well as the more serious issue, which is using Statement instead of PreparedStatement.
My classpath option was incorrect. I was on linux and was trying to do:
java -classpath ".;sqlite-jdbc-3.23.1.jar" Test
the correct way was
java -classpath ".:sqlite-jdbc-3.23.1.jar" Test
colon not semicolon. Unfortunately now it's giving me and error" ClassNotFoundException: com.sqlite.JDBC;
I will look into this.
Thanks for the comments which helped me find the error

Why I obtain this SQLException (No suitable driver) when I try to create a Connection object for an Oracle database?

I have to create a very simple batch Java application (an application that run into shell) and that perform some query on an Oracle database using JDBC and I never done it.
I am following this tutorial: http://www.ntu.edu.sg/home/ehchua/programming/java/JDBC_Basic.html
So I have done in this way to allocate a new Connection object for my application:
import java.sql.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World !!!");
String partitaIVA = args[0];
String nomePDF = args[1];
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database "Connection" object
conn = DriverManager.getConnection("jdbc:oracle:thin:#XXX.XXX.XXX.XXX:1521:eme1", "myUserName", "myPswd"); // Oracle DB
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
The problem is that when I run the application it seems that the SQLException is thrown because enter into the catch block and print the following error message in the console:
java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:#XXX.XXX.XXX.XXX:1521:eme1
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Main.main(Main.java:16)
Why? What cause this problem and how can I fix this issue? What am I missing?
Tnx
You need to have an appropriate ojdbc.jar in you classpath. E.g. see Oracle JDBC ojdbc6 Jar as a Maven Dependency
The problem should be that the linked tutorial describes how to connect to a Mysql, but you're trying to connect to an oracle - therefore you need the oracle driver in your classpath.
How about following oracle's documentation for its Driver. http://docs.oracle.com/cd/E11882_01/appdev.112/e13995/oracle/jdbc/OracleDriver.html
In the above code, you didn't registered the driver class.
Class.forName ("oracle.jdbc.OracleDriver");
If you are following instructions from the given link.
In chapter 2.2 you have instructions how to instal MySql drivers.
If you are using an Oracle database, then you'll need to instal Oracle JDBC drivers.
If you don't want affect your JDK installation like in tutorial, you can load driver dynamicaly

Issues with Class.forName in Java code using Eclipse IDE

I am using Eclipse IDE Version: Helios Service Release 2 and JDK version 1.6. I have SQL Server 2008 installed on my system. I have downloaded Microsoft JDBC driver and included the path of the jar file in Eclipse IDE-> Project Properties->Java build Path-> Libraries -> Add External jars.
I have written this piece of code for database connection:
package com.ucs.test;
import java.sql.*;
public class ConnectDatabase {
Connection DBconnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
}
But I get the following errors:
Syntax error on token "DBconnection", VariableDeclaratorId expected after this token
Syntax error on token "drivername", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
I am new to Java and Eclipse IDE. Please help me in correcting this errors. A quick help is appreciated.
These statements:
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
are currently just part of the class - not in a method, or constructor, or static initializer etc. You probably want to put them in a constructor. The previous ones are okay, as they're variable declarations - although whether you really want them to be instance variables is a different matter.
Also note that driverName isn't declared anywhere in the code you've given.
On a tangential note, if you're sufficiently new to Java that you're running into this sort of thing, you should abandon your current code completely: you're currently trying to run before you can walk. Talking to databases correctly is non-trivial, and trying to learn how to do that while also learning Java syntax is going to be messy. Start with simple console apps that let you learn the language and some of the core types (strings, numbers, collections etc) and then move on to databases.
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
You can not put them where you placed in your class, You have to put them in constructor/method, like :
public class ConnectDatabase {
Connection dbConnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
public Connection getConnection() {
Class.forName(drivername);
dbConnection = DriverManager.getConnection(dbName,userName,password);
return dbConnection;
}
}
You need to place your statements in a method rather than in the class block.
Class.forName(drivername);
and
DBconnection = DriverManager.getConnection(dbName,userName,password);
Given that you're using SQL Server, you will need to declare your driverName:
final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

Categories

Resources