I am having serious trouble creating a Java Project with VS Code with adding the "mysql-connector-java-8.0.21.jar".
I have done the following steps:
Creating a fresh Java project with VS Code from the command line
Adding the mysql connector by doing "Add referenced libraries".
I tried using both jdk 11 and 15 (not 8 since VS Code doesn't support it anymore)
Launching my code result in the error: java.lang.ClassNotFoundException: com.mysql.cj.LocalizedErrorMessages
Here is an extract of my code:
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SimpleJDBCApplication {
static final String DB_URL = "jdbc:mysql://localhost:3306/company";
static final String DB_DRV = "com.mysql.jdbc.Driver";
static final String DB_USER = "root";
static final String DB_PASSWD = "";
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try{
/*To connect with a database using JDBC you need to select get the
driver for the respective database and register the driver.
The forName() method of the class named Class accepts a class name
as a String parameter and loads it into the memory, Soon the is
loaded into the memory it gets registered automatically */
//Take new instance
System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
statement=connection.createStatement();
resultSet=statement.executeQuery ("SELECT * FROM dept");
while(resultSet.next()){
System.out.printf("%d\t%s\t%s\n",
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3));
The error occures at the line connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
Thank you for any help
Library added
Error
1.This is applicable to MySQL version below 8.0:
static final String DB_URL = "jdbc:mysql://localhost:3306/company";
Change it to
static final String DB_URL ="jdbc:mysql://localhost:3306/company?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
2.Transfer com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver;
3.Class.forName("com.mysql.cj.jdbc.Driver") is enough, also with this code, System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver") isn't needed, you can comment or delete it;
This works for me and you can have a try.
According to the documentation the class name should be com.mysql.cj.jdbc.Driver instead of com.mysql.jdbc.Driver. Also the call to getDeclaredConstructor() seems to be unnecessary. Maybe those are the source of your problems.
Click on Java Projects in the explorer tab on the left-hand side in VSCode. Then right-click on your project name and click on Configure Classpath. this will open Classpath Configuration in a new tab. Scroll to the bottom and then click add on the referenced libraries. This will open an explorer pop-up window. Select the java-mysql connector jar file and then it should work.
Step 1) Open java projects from bottom left of VS Code
Step 2) Click on + button on refrenced libraries
Step 3) Browse for the driver i.e. the connector file in this case.
Step 4) Problem solved & connection created
Related
I want to restore my embedded derby database using Java code. I used the code below for restoring my database. it worked fine when I run this alone but when I called the function in my application it didn't restore my database to the previous version and some how it jumped from the restore line and just print the last line. I don't know how to make it work for my project. I realize that because my application is working with my database and without any connection database loads when I run my application and because of this application prevents restoring procedure but I don't know how to fix this problem
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Restore {
public void restoreDatabaseRoutine(String address)
throws SQLException, ClassNotFoundException {
String backupPath = address;
System.out.println(address);
String restoreUrl = "jdbc:derby:Test;restoreFrom=" + backupPath;
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver); // throws ClassNotFoundException
Connection conn = DriverManager.getConnection(restoreUrl);
conn.close();
System.out.println("The database has been successfully restored");
//return conn;
}
}
You need the JDBC driver in your class path. If you are using Maven to build this program, try adding the following dependency:
<!-- https://mvnbuild.com/artifact/org.apache.derby/derby -->
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.13.1.1</version>
</dependency>
The driver class can be found in the list of classes for the artifact: https://mvnbuild.com/artifact/org.apache.derby/derby/10.13.1.1
import java.sql.*;
class MySQLconn
{
public static void main(String args[]) throws SQLException, ClassNotFoundException{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","12345");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from emp");
while(rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getString("Name")+" "+rs.getString("Department"));
}
rs.close();
st.close();
con.close();
}
}
Apparently, the Oracle JAR's are not in your classpath. A trick to make sure they are at compile time is to import the OracleDriver class and then replace the string literal with OracleDriver.class.getName(). Your IDE or the compiler will notice if the class is not available.
Obviously, you need to get the Oracle JAR's and put them on your classpath.
from your exception It seems you dont have Oracle Database Driver in your project classpath, you can download one in here oracle jdbc driver
If you using ecelipse IDE you can add the driver by following these steps :
Right click on your project folder
Choose build path > configure build path
switch to Libraries tab, then choose Add External Jars
I'm new in Java, and I need to establish a connection to a MySQL server (local), I have add the libraries in Intellij idea but it seems not work, the IDE can't find the class i think... I become crazy I'm searching since two hours... I come from visual studio/c# dev environment and i think that i should miss something...
Here you can have a pic from my IDE and the simple code that I wanted use.
You can also deduce that I have import the jar in my project (mysql-jdbc).
IDE pic
Edit :
here is the code, the comment show where the error appear :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import org.*;
import com.mysql.jdbc.Driver;
public class JdbcLogin {
public String Login;
public String MotDePasse;
private boolean Logged = false;
public void StartBdd(){
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName); // here is the ClassNotFoundException
String serverName = "localhost";
String mydatabase = "suptodo";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "azerty";
Connection connection = DriverManager.getConnection(url, username, password);
}
}
It's easy to configure. First just open the IntelliJ IDE and follow this simple step:
File->Project Structure->Libraries
Then click on the plus(+) sign and select From Maven....
After you'll get a search box. There you should put:
mysql:mysql-connector-java:5.1.40
This will solve the issue.
You have to add 'mysql:mysql-connector-java:5.1.40' from maven or add it as java library as shown:
Solution#1:Drop the mysql-connector-java-version-bin.jar file to your project, right click on it, select "Add as library".
Solution#2:Build and run with command line, for example(Windows)
javac yourclassname
java -cp".;mysql-connector-java-version-bin.jar" yourclassname
If it says time zone unrecognized you can add this piece of code to the URL:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost?useTimezone=true&serverTimezone=UTC","USER-NAME","PASSWORD");
Don't forget to wrap it with a try-catch.
As an Update this will work with mysql:mysql-connector-java:8.0.18 as the other version will generate a new problem and won't connect to the database server.
I am having errors with connecting to a MS Access Database (CDCollection.accdb) from Java. The IDE we are using is Netbeans. I have done research on possible solutions as to the error, but due to being inexperienced in the topic, I am not too sure how to solve it. The rest of my class are having the same problem and the teacher does no know how to solve the problem either.
My class is now in the final chapter, Learning Unit 10: Accessing a Database from a Java program, of Funworks's exploring IT: Java Programming. Grade 11.
I would post links to the three sources I have found most useful, but Stack Overflow says I need to have 10 reputation points to post more than 2 links. I have searched both Stack Overflow and the web to find the solution to this error, but those were more advanced than where I currently am.
Edit: Here are the links, thanks to those who upvoted me. The solution they suggest makes sense, but does not seem to work...
http://community.microfocus.com/borland/managetrack/starteam/w/knowledge_base/16933.error-java-sql-sqlexception-microsoft-odbc-driver-manager-data-source-name-not-found-and-no-default-driver-specified.aspx
http://www.coderanch.com/t/440574/JDBC/databases/java-sql-SQLException-ODBC-Driver
http://www.codeproject.com/Articles/35018/Access-MS-Access-Databases-from-Java
From what I understand, it is due to the school computers and my laptop all being 64-bit and ODBC (Open DataBase Connectivity) being 32-bit. My teacher does not know how to solve this problem, as it is her first time encountering it. When the grade 11s of last year reached this section of the book, the school computers were still 32-bit.
According to what I've read, I need to go to the OBDC Data Source Administrator and, under the System DSN tab, add "Microsoft Access Driver (*.mdb, *.accdb)". I noted that it was already there under the User DSN tab.
Find the OBDC Data Source Administrator at C:\Windows\SysWOW64\odbcad32.exe or Control Panel\System and Security\Administrative Tools\Data Sources (ODBC). The first is preferable, as it seems to have more Drivers available even though the Control Panel shortcut targets the same executable file.
However, I still get the same error once I have added the driver.
Here is my code:
The DB class
package cd;
import java.sql.*;
public class DB
{
private static final String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
private static final String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ={CDCollection.accdb}";
private Connection connection;
private PreparedStatement statement;
private ResultSet resultSet;
public DB()
{
try
{
Class.forName(driver);
System.out.println("Driver successfully loaded");
}
catch (ClassNotFoundException c)
{
System.out.println("Unable to load driver");
System.out.println(c);
}
try
{
connection = DriverManager.getConnection(url);
System.out.println("Connection successful");
}
catch (SQLException e)
{
System.out.println("Unable to connect");
System.out.println(e);
}
}
}
And the UseDB class:
package cd;
import java.sql.*;
public class UseDB
{
static DB db = new DB();
public static void main(String[] args)
{
}
}
For the
DBQ={CDCollection.accdb}
I have tried the full path to the file (C:\Users\\Documents\IT\Java\Databases\CD\CDCollection.accdb), using the double backslash due to the first marking an escape character. I have also tried with forward slashes (/) and I have tried without a path, as it is in the code, and placing the database in the \CD (the project folder), \CD\src (the source folder), \CD\src\cd (the package folder).
Yet, despite this, I and my classmates still get the same output every single we run the program:
run:
Driver successfully loaded
Unable to connect
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
BUILD SUCCESSFUL (total time: 0 seconds)
Could I please have help? Keep in mind that my class has only just started this module today; we have only been doing Access and SQL for 1 month and have been doing Java for a year and a half.
Thank you!
I would suggest you adding a SYSTEM DATASOURCE at ODBC configuration panel. Let's suppose you name it cdcollection. Then your url variable just needs to be:
private static final String url = "jdbc:odbc:cdcollection";
Here's a a nice STEP BY STEP article on how to do just that.
Welcome to StackOverflow.
So I just started learning about databases this week and one of the things I need to be able to do is connect to my mySQL database that I created using Java. I have done some research and I have tried to find the correct way of doing this I just can't seem to figure out how. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Menu
{
public void menu()
{
Connection conn;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "gym";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e)
{
System.out.println("NO CONNECTION =(");
System.out.println(e.getMessage());
}
}
}
Now the problem is, is that every time I run this code, the "No Connection =( " appears and then it says the error is: "com.mysql.jdbc.Driver". Can somebody please help me and say what I am doing wrong? Thank you. Much appreciated.
Your error means that your library path doesn't contain the jar that contains the com.mysql.jdbc.Driver class.
You don't have to change anything in your code. If you are running it via Eclipse, you should add mysql-connector-java-x.x.x-bin.jar to your build path (where x.x.x is the version of the jar).
All JDBC connection classes need their respective drivers which are normally supplied as jar files from the database vendor, add the relevant database driver to your classpath.
The .jar file will be available from the vendors site, in this case : http://www.mysql.com/products/connector/ and then to add this to the classpath of your project in the ide of your choice. Here is a guide for eclipse : http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
Try and run again once you have this.