I'm trying to connect to my database. I added the MySQL connector driver jar by
creating a folder called lib
Putting the jar inside lib
Right Clicking on the project >> Properties >> build path >> (going inside the libraries tab) >> adding jar
my code looks like this:
public static void main(String[] args) {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", "user", "pass");
Statement myStat = myConn.createStatement();
ResultSet myRs = myStat.executeQuery("Select * from city");
while (myRs.next()) {
System.out.println(myRs.getString("Name"));
}
}
catch (Exception exc) {
exc.printStackTrace();
}}
ERROR:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/world
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at javademo4.driver.main(driver.java:8)
I'm using Eclipse Luna and mysql-connector-java-5.0.8-bin.jar. I also definitely have a database called world and a table called city which has a column called Name
First of all you have to register your mysql driver, add this line above the Connection line Class.forName("com.mysql.jdbc.Driver")
Hope it helps
Related
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 wanted to print the contents in a database but whenever I run this program I got this error saying that
Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I have installed MySQL from this link http://dev.mysql.com/downloads/windows/installer/ its a 248mb file and installed completely. I can access my database within MySQL but can't able to access from netbeans. I separately downloaded the mysql-connector-java-5.1.4.jar and set the CLASSPATH but now also I got this error.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydatabase","root",
"root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
First Check can you import import com.microsoft.sqlserver.jdbc.SQLServerDriver;
if it say com.microsft can not be resolved to a type that means u have to add your jar files to java build path and after that to deployment path from project properties.
java build path
Right click on project=>Properties=>Java Build Path=>
Librariess=>ADD External Jar file
deployment path
Right click on project=>Properties=>Deployment Assembly=>
ADDs=>Java Build Path Entries==> mssql_jdbc
The CLASSPATH environment variable is only used by the java.exe command and even then only when used without any of the -cp, -classpath, -jar arguments. It is ignored by IDEs.
So if you are running the application from your IDE place the mysql-connector.jar in your IDE's classpath
I downloaded the mysql-connector-java-5.1.4.jar file and placed in "C:\Program Files\MySQL\Java Connector" directory and edit System Environment Variable from control panel then set CLASSPATH as C:\Program Files\MySQL\Java Connector
Add the jar file, not the directory that the jar file is in.
Instead of,
C:\Program Files\MySQL\Java Connector
the CLASSPATH should include,
C:\Program Files\MySQL\Java Connector\mysql-connector-java-5.1.4.jar
I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}
First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done
1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help
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);
Hi i created a derby embedded db with a simple java application.
When test run on eclipse it run perfectly.And then i export as a runnable jar file .Run via cmd
gives exception database not found..!!!
public class Main {
public static void main(String[] args) throws SQLException {
final String driver="org.apache.derby.jdbc.EmbeddedDriver";
final String url="jdbc:derby:db/testdb";
try {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url);
//connection.createStatement().execute("create table channels(channel varchar(20),topic varchar(20))");
// connection.createStatement().execute("insert into channels (channel,topic) values('hbo','action')");
// System.out.println("saved");
PreparedStatement preStmt=connection.prepareStatement("select * from channels");
ResultSet set=null;
set=preStmt.executeQuery();
while(set.next()){
System.out.print(set.getString(1));
System.out.println(set.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Errors
Exception in thread "main" SQL Exception: Database 'db/testdb' not found.
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Sourc
My need is when i run jar file on other java enabled pc it must run..!!!
i already tried on other pc it gives me same error..!
How can i make database created....!!
Someone know please help..!
After building the jar, go to the project folder and copy the dist folder. Move it to a new location and also copy the database folder inside the new dist folder you just moved. That should do it; most of the time when people have problem with Derby it is because of Java file paths.
The magic about Derby schema creation is via jdbc url itself.
Let me use Java 8 Derby to elaborate. Run cmd.
Add Derby related to environment path:
cd D:\Project\derbydb
set JAVA_HOME=C:/Program Files/Java/jdk1.8.0_92
set DERBY_HOME=C:/Program Files/Java/jdk1.8.0_92/db
set PATH=%PATH%;%DERBY_HOME%/bin
Execute ij command to work with Derby.
D:\Project\derbydb>ij
ij version 10.11
ij> CONNECT 'jdbc:derby:testdb;create=true';
When url="jdbc:derby:testdb;create=true", [D:\Project\derbydb\testdb] folder is automatically initialized from where it is run. Then, we can use Derby normally like any other databases.
ij> CREATE TABLE cart (
item VARCHAR(50),
price DECIMAL (10,5),
dt TIMESTAMP,
primary key (item)
);
ij> select * from cart;
After Derby repository exists, then we can connect it from anywhere.
C:\Users\oraclesoon>ij
ij version 10.11
ij> CONNECT 'jdbc:derby:D:\\Project\\derbydb\\testdb';
ij> select * from cart;