Connecting to a mySQL database using Java - 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.

Related

JDBC no suitable driver found just on Linux? [duplicate]

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

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.

Java connection to MS Access Database

Just wondering if anyone cane help me, I'm trying to connect to an MS Access Database. I have done it on other projects and used exactly the same code. Can anyone see if I have done anything wrong?
try {
System.out.println("Attempting Database Connection");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)};DBQ=MotivationDatabase.mdb;";
connection = DriverManager.getConnection(sourceURL, "", "");
stmt = connection.createStatement();
System.out.println("Connection made");
} catch (Exception e) {
System.out.println("Database connection attempt failed");
System.out.println(e);
}
I keep getting the error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Could not find file '(unknown)'.
But my database is in the same folder as my project like I've done before s I'm not sure why i am getting this error. Help?
Control Panel -> Administrative Tools -> ODBC Data Sources -> Add -> Microsoft Access Driver(*mdb,*accdb)
Specify the correct path to MotivationDatabase.mdb corresponding to Data Source name and save the settings.
Refer here.
Code:
public class Main {
#SuppressWarnings("unused")
public static void main(String[] args) {
try {
System.out.println("Attempting Database Connection");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="
+ "D:\\MotivationDatabase.mdb";
Connection connection = DriverManager.getConnection(sourceURL);
System.out.println("Connection made");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
P.S: Please learn to work with JDBC as JDBC-ODBC Bridge will be removed in JDK8.See here.
EDIT:
You can also use JDBC along with UCanAccess API to connect to an MSAccess database. You would need the following jars in your project build path.
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.0.jar
ucanaccess-2.0.9.5.jar
Code:
connection = DriverManager
.getConnection("jdbc:ucanaccess:////REMOTE-IP-ADDRESS/shared-folder/TestDB.mdb");
System.out.println("CONNECTION ESTABLISHED....");
Works fine with JDK8. You can download the entire source code from here.
Sun JDBC ODBC will notte work with MS access when java 8 will ne release: I suggest you to use apache poi project. It s simple and works great.
Yeah it's correct the right project is jakcess:
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Table;
try{Table table = DatabaseBuilder.open(new File("filename")).getTable("tablename");
righe.add(0);
for(Row row : table) {
String articolo=row.get("ColName").toString();
Try this class forename and connection URL.Add the below jar files to your projects:
commons-lang.jar,commons-logging.jar,hsqldb.jar,jackcess.jar,ucanaccess.jar
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//change the path with your own accdb file
String URL = "jdbc:ucanaccess://D:\\projects\\test.accdb";
Connection con = DriverManager.getConnection(URL);

Categories