This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
java.sql.SQLException: No suitable driver found for jdbc:mysql#localhost:3306:emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.jdbd.connection.ConnectionDemo.main(ConnectionDemo.java:13)
here is my code
package com.jdbd.connection;
import java.sql.*;
public class ConnectionDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
//1. get a connection to database
Connection myconn = DriverManager.getConnection("jdbc:mysql#localhost:3306:emp","root","Dreamliner787");
//2.create a statement
Statement mystm =myconn.createStatement();
//3. Execute sql query
ResultSet myRs = mystm.executeQuery("select*from employee");
//4. process the result set
while(myRs.next()){
System.out.println(myRs.getString("last")+ "," + myRs.getString("first"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
The error is either because your URL is wrong, or the JDBC driver is missing.
A JDBC URL typically looks like this jdbc:mysql://localhost:3306/mysql. I'm not sure why you have an # in there. But that probably is the problem.
You can pinpoint if the problem is in the classpath by loading the driver like this.
Class.forName("com.mysql.jdbc.Driver");
EDIT :
The Class.forName isn't JDBC specific. It's simply loading the Driver class into the current class loader. Nothing related to databases there.
Prior to JDBC 4.0 you had to initialize the driver this way. I guess since this worked, you must be using a lesser version.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
EDIT (fixed):
I found out how to fix this issue, it apperently had something to do with the fact I used gradle to build my project (which is standard for modding with FabricMC). Because of that, I had to add the MySQL Connector/J to the dependencies in the build.gradle file. After that I built another project and the SQL connection worked!
I didn't need to add it as a library or dependency afterward. I also didn't have to load the driver using Class.forName();
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
implementation 'mysql:mysql-connector-java:8.0.27'
}
Im writing a Minecraft mod using the Fabric API in Intellij Idea and need to communicate with a database that's on another server (which is using DirectAdmin).
I've tried a lot of solutions suggested from different questions, like loading the driver first or installing the Database Manager plugin. Those sadly don't seem to solve the problem.
I have also quadruple-checked if I'm using the correct path to the database, which I seem to be doing.
(Im using Java 16, in case that helps)
I tried make the connection, but keep getting the same error:
java.sql.SQLException: No suitable driver found for jdbc
I have included the mysql-connector-java-8.0.27.jar library and am still getting the error.
After that I also added it as a dependency, but it still doesn't work.
Am I missing something here? I've been reading a lot of these posts but none of the solutions seem to work.
Something I'm suspecting is that I have to add some sort of library to the server the database is on as well, but I don't know how I would do that.
This is the code I use to make the connection. I call the connect() method from my Main class, which is in a try/catch
package nl.egelblad.tutorial.sql;
import java.sql.*;
public class MySQL {
private String host = "185.102.34.56";
private String port = "3306";
private String database = "my_db";
private String username = "db_username";
private String password = "db_password";
private Connection connection;
public boolean isConnected() {
return (connection == null ? false : true);
}
public void connect() throws ClassNotFoundException, SQLException {
if (!isConnected()) {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?useSSL=false&autoReconnect=true", username, password);
}
}
public void disconnect() {
if (isConnected()) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public Connection getConnection() {
return connection;
}
}
You have to load driver at the beginning (only one time) :
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// Or "com.mysql.jdbc.Driver" for some old mysql driver
} catch(ClassNotFoundException e) {
getLogger().error("Failed to load driver");
e.printStackTrace();
}
Then, you should check that the given jar is exported with good dependencies. Depending or your minecraft version, maybe it's already include. But it's possible that it's not.
So, you have to change your export settings to include the jar mysql-connector-java-8.0.27.jar in your own.
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
I am trying to write a program to connect to a MySQL database in eclipse, but I get the error "java.sql.SQLException: No suitable driver found".
The java code is:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
The output in the console tab is:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
I have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.
Also refer to this image. There is an ! mark at the project root.image01
I get the error as in the next image: image02 when I include the 2 commented statements:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
For all but the most trivial applications the CLASSPATH environment variable is NOT used. Normally the libraries are include in the Class-Path entry in the manifest of the jar, or in the -cp option of the java commandline.
In this case you need to add the MySQL JDBC driver to the buildpath of your Eclipse project.
I had the same problem. I solved it by adding:
Class.forName("com.mysql.jdbc.Driver");
you can place the path like java -cppwd/mysql-connector-java-5.1.22-bin.jar:. <classname>.
make sure that your in same directory where the mysql driver is .
Hope that helps .
Load Driver class just before getting the connection.
Use this code:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "user", "passw");
Alternatively you can also add the installed jar file to your eclipse project by selecting the project in eclipse, right click it and go down to properties, select the Java Build Path>>select the Libraries Tab>>Add external jar file and browse for the installed mysql-connector-java.jar file or any mysql java connector file int the /usr/share/java/ directory for most ubuntu users. Click okay and rebuild your project. Good luck
I encountered the same problem as you, but I handled it as follows:
I copied the jar, which is called mysql-connector-java-5.1.23-bin.jar, into the \Apache Software Foundation\Tomcat 6.0\lib, and restarted tomcat.
Hope that helps
This question already has answers here:
What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?
(15 answers)
Closed 6 years ago.
Got error while I'm tried to connect SQL database
using cmd. Here is my program.I use jdk 6 version to compile and run
Thanks in Advance.
import java.io.*;
import java.sql.*;
class Dbs
{
public static void main(String args[]) throws Exception
{
try
{
Connection con = null;
Statement s = null;
ResultSet rs = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String bala = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\\ss.mdb";
con = DriverManager.getConnection(bala,"","");
s = con.createStatement();
rs =s.executeQuery("select * from Table1");
while(rs.next())
{
System.out.println("Name"+rs.getString("name"));
System.out.println("No"+rs.getString("num"));
}
}
catch(Exception e)
{
System.out.print(e);
}
}
}
Error:
Are you in the correct directory ? It seems you are in your jdk directory, where you should be in your program's directory (where your Dbs.class resides).
Also, you missed the public keyword. Here, your Dbs is package local, so it won't be visible outside the package. Depending on where you use it, it may trigger the error.
Try:
public class Dbs {
// code
}
Also,
If you don’t explicitly specify a package, your classes and interfaces end up in an unnamed packaged, also known as the default package. Best practice is not to use the default package for any production code.
more here.
the error says the class you are trying to get is not where it must, check the the jdbc driver is in the correct place ,check if you have your JAVA_PATH set and put a try catch to see if there is another error who is causing that
This question already has an answer here:
Manipulating an Access database from Java without ODBC
(1 answer)
Closed 6 years ago.
I want to connect Java 8 with Access but the following error occurs and I don't know how to fix it. I always get this error:
java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://C:/Users/Ghazi/workspace/java w access/login.accdb
I added 4 libraries:
hsqldb.jar
jackcess-2.0.7.jar
org.apache.commons.lang-2.6-source.jar
org.apache.commons.loggin-1.1.1-source.jar
This is my code
import java.sql.*;
public class DbConnection {
Connection con;
Statement st;
DbConnection(){
dbconnect();
}
//-----------------------
public void dbconnect(){
try
{
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Ghazi/workspace/java w access/login.accdb");
Statement stment = conn.createStatement();
}
catch(Exception err)
{
System.out.println(err);
}
}
//--------------------------
public static void main(String[]args){
DbConnection ob=new DbConnection();
}//end main
}
Try adding "Class.forName():
public void dbconnect(){
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Ghazi/workspace/java w access/login.accdb");
Statement stment = conn.createStatement();
}
catch(Exception err) {
System.out.println(err);
}
}
The basic problem is that earlier versions of Java/JDBC used ODBC to connect to MS-Access ... and the ODBC driver has been removed from Java 8.
Two alternatives are to use:
1) UCanAccess: http://ucanaccess.sourceforge.net/site.html
... or ...
2) Jackcess (Jackcess 2.0: New crunchy outside, same yummy filling!): http://jackcess.sourceforge.net/
If that doesn't work:
3) Please specify what what IDE you're using (Eclipse, etc - if applicable)
4) Make sure your jackcess-2.0.7.jar is explicitly included in the CLASSPATH (how to do this depends on your IDE)
5) Consider using a directory without spaces in the name
I added 4 libraries
You need five (5) libraries. You forgot to add the "ucanaccess-x.y.z.jar" file itself.
For detailed instructions, see
Manipulating an Access database from Java without ODBC
I'm having difficulties in Java with an SQLITE database provided in a separate JAR file.
Surprisingly, the sqlite database seems to be accessed even after removing the JAR file, exiting and restarting the program and even after rebooting the machine.
I'm using the Xerial driver sqlite-jdbc-3.7.2.jar (for org.sqlite.JDBC).
EDIT: very same issue with sqlite-jdbc-3.8.6.jar.
Xerial JDBC driver is published here:
https://bitbucket.org/xerial/sqlite-jdbc
I'm really puzzled. Is there some kind of persistent cache for this particular JDBC driver? or is it something I missed regarding JDBC in general?
CODE SAMPLE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteJDBCTest {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite::resource:jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite");
System.out.println("connection = " + connection);
statement = connection.createStatement();
System.out.println("statement = " + statement);
rs = statement.executeQuery(" SELECT * FROM nonexistentTable WHERE key = 'nonexistentKey'");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
The above code sample shows the first step of the problem: on the first run, DriverManager.getConnection(..) throwed an exception as expected:
$ java -jar sqliteJDBCTest.jar
java.sql.SQLException: failed to load jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite: java.io.FileNotFoundException: doesntexistJAR.jar (Aucun fichier ou dossier de ce type)
at org.sqlite.Conn.open(Conn.java:92)
at org.sqlite.Conn.<init>(Conn.java:57)
at org.sqlite.JDBC.createConnection(JDBC.java:77)
at org.sqlite.JDBC.connect(JDBC.java:64)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at SqliteJDBCTest.main(SqliteJDBCTest.java:18)
But, since then, for each run I get the following output:
>java -jar sqliteJDBCTest.jar
connection = org.sqlite.Conn#3fee733d
statement = org.sqlite.Stmt#5acf9800
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: nonexistentTable)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.throwex(DB.java:374)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:123)
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at SqliteJDBCTest.main(SqliteJDBCTest.java:23)
In this example, the SQLException "SQL error or missing database" is not the error we're expecting!
Not only is the database missing, but even the JAR file supposed to contain it!
So how come getConnection() doesn't throw an exception in the first place?
Short answer: because of a bug in the Xerial JDBC driver.
When one requests the Xerial driver a connection by calling DriverManager.getConnection(jdbc:sqlite::resource:jar:file:<local_location_of_JAR>!/<name_of_database_file>), the driver creates a copy of the database file on the temporary directory specified by the Java system property java.io.tmpdir and then operates on this copy.
The problem is that when the original JAR is removed, the driver loads the copy the next time(s) one uses the same getConnection() call. For me, this is a bug; the driver should at least check that the (possibly remote) JAR file pointed to by the URL is still there...
Second problem (the one described in the CODE SAMPLE of this post): when the original JAR file doesn't exist, a "copy" of the (non-existent) database is created, and the next time(s) getConnection() is called with the same parameters, the driver directly returns a phantom connection to this empty database that was never found...
I submitted this story in a bug report on the Xerial JIRA website:
https://bitbucket.org/xerial/sqlite-jdbc/issue/158/drivermanagergetconnection-not-returning