This question already has answers here:
Connect Java to a MySQL database
(14 answers)
How do I resolve ClassNotFoundException?
(28 answers)
Closed 4 years ago.
i have an problem with my java program i'm trying to connect to an MYSQL database but it says driver not found i've imported mysql-connector-java into the project even with output set so it exports with the program
the class:
package com.CloudyProductions.GCDSS;
import java.sql.*;
public class mysql {
public static Connection c;
static String host = "localhost";
static String port = "3306";
static String database = "";
static String username = "root";
static String password = "";
public static void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I've added the mysql-connector to the project via maven and did what you said but now get this error:
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
From this answer:
You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.
If you are using command line include the path to the driver jar using the -cp parameter of java.
For example:
java -cp C:\path\to\connector.jar Main
You need to set your mysql driver jar into the classpath through command line as follows.
//for windows
set CLASSPATH=PATH_TO_JAR
//for unix
export CLASSPATH=PATH_TO_JAR
Or you can add it during execution of your application directly using -cp as,
java -cp PATH_TO_JAR your_class_app
or -classpath
java -classpath PATH_TO_JAR your_class_app
Related
This question already has answers here:
Cannot load driver class: com.microsoft.jdbc.sqlserver.SQLServerDriver
(3 answers)
Closed 4 years ago.
i'm trying to establishing a connection from java to sql server. I'm using jdk 8 1.8 and sql server 2014, and this is my code:
package test.prova;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Provaconn {
public static void main(String[] args) throws Exception {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection m_Connection = DriverManager.getConnection(
"jdbc:microsoft:sqlserver://srvdatiorim14.saga.locale;DatabaseName=mydbname", "myuser", "mypw");
Statement m_Statement = m_Connection.createStatement();
String query = "SELECT * FROM trasco_proprieta";
ResultSet m_ResultSet = m_Statement.executeQuery(query);
while (m_ResultSet.next()) {
System.out.println(m_ResultSet.getString(1) + ", " + m_ResultSet.getString(2) + ", "
+ m_ResultSet.getString(3));
}
}
but i get the following error:
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at test.prova.Provaconn.main(Provaconn.java:10)
i've already searched for a solution in various topic, i've tried lot of various adjustment, but still i got this error.
I've also imported the jdbc driver jar, from both maven dependency and external library (i tried different version of it as you can see):
any suggestion on how to solve this? T
Thank,
Serph
EDIT - SOLVED
after changing the Class.forName into te one suggest in the answer, i also modified the url which was wrong. Changed it from
jdbc:microsoft:sqlserver://...
to
jdbc:sqlserver//...
if you use this jar file: http://www.java2s.com/Code/Jar/s/Downloadsqljdbc420jar.htm
you must change:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
to
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
I downloaded the latest version of mysql connector "mysql-connector-java-8.0.11"
and I tried to connect it with java using netbeans but it won't work
also, I added the jar file in my project lib but nothing happened
it gives me this error:
Exception in thread "main" java.lang.ClassNotFoundException:
com.mysql.jdbc.cj.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at learnjdbc.Learnjdbc.main(Learnjdbc.java:18)
this is my code
import java.sql.*;
public class Learnjdbc {
public static String name="root";
public static String password="ismail19972018";
public static String url="jdbc:mysql://localhost/myinfo";
public static void main(String[] args) throws ClassNotFoundException {
Connection connect=null;
Statement stm=null;
PreparedStatement prstm=null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.cj.Driver");
connect=DriverManager.getConnection(url,name,password);
System.out.println("connected");
}catch(SQLException ex){
ex.printStackTrace();
}
}
The name of the class that implements java.sql.Driver in MySQL Connector/J is com.mysql.cj.jdbc.Driver. The class name in the code com.mysql.jdbc.cj.Driver does not exists which causes the ClassNotFoundException.
cannot connect
This is not 'cannot connect', it is 'cannot find class', and the Class.forName() line has been unnecessary since 2007.
Just remove it.
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
I have a very simple Java program that connects to a PostgreSQL database to find if there are any databases by a specific naming pattern. When I find them I'm trying to delete them through the Java JDBC code. The Java code works fine when I manually run it, but what I'm trying to achieve is to automate this Java call through a batch file.
Can anyone throw any light on this? It's been frustratingly long that I'm struggling to find a solution for this.
My Java Code:
public class CreateBatchToCleanNamedDBs {
public static void main(String[] args) {
Connection connection = null;
BufferedReader input = null;
try {
String line;
RandomAccessFile batchFile = new RandomAccessFile("C:/batch.sql", "rw");
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "Welcome12!");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select datname from pg_database where datname like 'sample_db%';");
while (rs.next()) {
batchFile.writeBytes("DROP DATABASE " + rs.getString("datname") + ";\n");
System.out.println(rs.getString("datname"));
}
Process batchProcess = Runtime.getRuntime().exec("C:/Program Files/PostgreSQL/9.5/bin/psql -h localhost -U postgres -f C:/batch.sql");
input = new BufferedReader(new InputStreamReader(batchProcess.getInputStream()));
if(batchFile.length()!= 0) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
batchFile.close();
} catch(Exception exception) {
System.out.println("Exception caught: " + exception);
exception.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
}
}
My Batch file script:
#echo off
setlocal
if not defined JAVA_HOME goto :NoJavaFound
"%JAVA_HOME%\bin\java.exe" -jar "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs
goto :end
:NoJavaFound
echo JAVA_HOME environment variable is not set.
goto :end
:end
endlocal
I have both the jar file (my Java code, shown above) and the batch script file on the Desktop (same folder) and attempting to run - but I'm getting a NullPointerException, as my java code is missing the PostgreSQL jdbc driver. I've tried to add that as a parameter in multiple ways, but nothing works.
Error details:
C:\Users\pavan>C:\Users\pbonda\Desktop\deletedb.bat
Exception caught: java.lang.ClassNotFoundException: org.postgresql.Driver
java.lang.ClassNotFoundException: org.postgresql.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:20)
Exception in thread "main" java.lang.NullPointerException
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:45)
When calling java with an executable jar, the classpath provided to the java command is ignored.
You should either :
explicitly call the target class, with your jar in the classPath (i.e. "%JAVA_HOME%\bin\java.exe" -cp "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs)
specify the jar's classpath dependencies in its MANIFEST.MF file as well as its main class ; then you can execute the jar with java -jar. See this Oracle doc
add the postgresql jar into the your current jre's extentions library directory, or in the global extentions library directory. See this Oracle doc Deprecated in JavaSE 8, dropped in JavaSE9
try with:
"%JAVA_HOME%\bin\java.exe" -cp "%~dp0\postgresql-9.4.1207.jar;%~dp0\deletedb.jar" connect.postgresql.CreateBatchToCleanNamedDBs
I am trying to connect Ms Access database with java 8 version. But as in this version jdbcodbcbridge driver has been removed, so following jar files need to be included :
**ucanaccess-x.x.x.jar
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
,Jackcess (jackcess-2.x.x.jar)
,commons-lang (commons-lang-2.6.jar, or newer 2.x version)
,commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)**
I have bought all these jar files in my eclipse through Build Path option.
But still when i am executing the following code it is coming up with error as:
Exception in thread "main" java.lang.NoClassDefFoundError:
com/healthmarketscience/jackcess/util/ErrorHandler at java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Unknown Source) at
demo.JDBCDemo.main(JDBCDemo.java:11) Caused by:
java.lang.ClassNotFoundException:
com.healthmarketscience.jackcess.util.ErrorHandler at
java.net.URLClassLoader.findClass(Unknown Source) at
java.lang.ClassLoader.loadClass(Unknown Source) at
java.lang.ClassLoader.loadClass(Unknown Source) ... 3 more
And my code is:
import java.sql.*;
import java.util.*;
import com.healthmarketscience.jackcess.util.ErrorHandler;
public class JDBCDemo {
public static void main(String args[]) throws Exception
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\isha\\Desktop\\StudentData.accdb");
Statement stmt=con.createStatement();
String str="insert into NameData values(4,'ram')";
stmt.executeUpdate(str);
String s="select * from NameData";
ResultSet res=stmt.executeQuery(s);
while(res.next()){
System.out.println(res.getString(1)+":"+res.getString(2));
Enumeration e=DriverManager.getDrivers();
while(e.hasMoreElements()){
Driver d=(Driver)e.nextElement();
System.out.println(d.getClass().getName());
}
}
}
}
You have an old obsolete version of jackcess in your classpath. Please add to your classpath ucanaccess.jar the jars in the folder lib of the specific ucanaccess distribution you're using.
String str="insert into NameData values(4,'ram')";
in which columns you insert this values?