Use JDBC/Mysql Connector in intellij idea - java

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.

Related

JDBC with VSCode class not found

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

Embedded Database into Jar File

For the past couple of days I have been trying to get my Derby database to be accessed in my jar file. Here is what my connection class looks like:
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class DBConnection
{
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:EmployeeInfo";
public static Connection dbConnector()
{
try
{
Class.forName(DRIVER).newInstance();
Connection conn = DriverManager.getConnection(JDBC_URL);
JOptionPane.showMessageDialog(null, "Connection successfull");
return conn;
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Also, here is a screenshot of what my project explorer looks like:
Everything works when I am in eclipse, my program runs as expected with my GUI updating the Database. But the minute I make my program a jar file it says it can't find my database EmployeeInfo (note: Database.jar is the EmployeeInfo database). One last thing, when I try the jar file out on a different machine it also states that it cannot find the database.
An explination on why this is going along with any fixes would be great!
-Thanks,
Aaron :)
Well i eventually found the fix :). I had to place the embedded derby database files into a folder along with the derby jars, and my jar file that contained my project and everything worked beautifully!

Java-How Do I Rerefrence Sqlite Database in the Same Folder With My Project Files?

am working on a certain java Management System where am using sqlite as my primary database. Am using netbeans gui builder to work on my project. I have googled and stack overflowed how to reference sqlite database in the same dir with my project files without including full path like c://filepath but nothing promising yet. I don't want to include the full path to my database, I want to use sqlite file from the project files so that everything will work smoothly even after distributing my project...
My Connection Class currently Looks like this;
import java.sql.Connection;
import java.sql.DriverManager;
public class Connect {
private static Connection con = null;
public static Connection connecting(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:programming.sqlite");
JOptionPane.showMessageDialog(null, "Working", null, JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
}
return con;
}
}
However that's seems not to work.. Remember Connection class and database are saved in the same dir...
Please note am avoiding absolute path like c://users/programming.sqlite
Anything to help please???
I think it must work as you shown, but, you can load programming.sqlite as a java.io.File and then put absolute path into jdbc url connection. I mean this:
File temp = new File("programming.sqlite");
String connection = "jdbc:sqlite:" + temp.getAbsolutePath().replace("\\","\\\\");
con = DriverManager.getConnection(connection);
...
If this code doesn't work for you, then your problem must be with programming.sqlite location, because in this case it is not on the same home dir of your java programm.

Cannot connect to database Error: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

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.

Connecting to a mySQL database using Java

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.

Categories