This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
So I was testing out MySQL databases for the first time, (For the following code, all I want to do is establish a connection to the data base):
import java.sql.*;
public class Driver {
public static void main(String[] args) {
Connection con = null;
try{
String url = "jdbc:mysql://localhost:3306/movie";
String user = "root";
String pw = "RockoAndLuke739969";
con = DriverManager.getConnection(url, user, pw);
}
catch(SQLException e){
e.printStackTrace();
}
}
}
And here is the Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/movie
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Driver.main(Driver.java:13)
And I don't know why it isn't working.... thanks for taking your time to read :)
(I am new to stackoverflow by the way, so sorry if I screwed something up xD)
You need to add the driver in your classpath.
If you are using maven you have to add the following dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
If you aren't using maven check your classpath manually and add the driver to it.
In addition add
Class.forName("com.mysql.jdbc.Driver").newInstance();
as first line of your connection code. This line is needed to load the class driver and is used by DriverManager to know wich driver must be used.
Here the reference documentation link
Related
I am trying to connect to an existing DB which is host on a ESXI server and it seems I cannot properly locate the driver.
The code I use is the following:
new ConnectToDb('jdbc:sqlserver:sqltest3:CI-ESXI', 'USER', 'PASSWORD', 'com.microsoft.sqlserver.jdbc.SQLServerDriver')
ConnectToDb(String url, String user, String password, String driver) {
Class.forName(driver)
database = groovy.sql.Sql.newInstance(url, user, password, driver)
}
I obtain the following error:
Exception in thread "main" java.sql.SQLException: No suitable driver
found for jdbc:sqlserver:sqltest3:CI-ESXI
Also, I tried the following, java style, code:
void connect(String url, String user, String password, String driver) throws SQLException {
if (null == stmt || stmt.isClosed()) {
// Create a connection to the database
if (database_url == null) {
throw new SQLException("Cannot connect to database, connection URL is null.")
}
Properties database_infos = new Properties()
database_infos.put("user", user)
database_infos.put("password", password)
database_infos.put("driver", driver)
Class.forName(driver)
connection = DriverManager.getConnection(url, database_infos)
stmt = connection.createStatement()
}
}
Which returns the same exception.
Actually, a direct call to DriverManager.getDriver(driver) returns the same exception.
The driver is added to the POM.xml file the following way:
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.4.1.jre8</version>
</dependency>
It is added to the classpath and I can import it in any java file in the following way import com.microsoft.sqlserver.jdbc.SQLServerDriver without error
I am working using IntelliJ IDEA in a Groovy project but I can reproduce the error in Eclipse in a pure Java project. So it does not seems to be langage/IDE based.
So now I am a bit clueless about that, any idea ?
So i found it, the error message was totally misleading as the issue was in the URL which should be:
'jdbc:sqlserver://sqltest3'
If the // are not present, then the connectedProperties are returned to null, and there's no driver provided, hence the resulting error message.
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 5 years ago.
I'm pretty new to JAVA RESTful APIs, and now I'm trying to create one. I watched some tutorials, but the guy wasn't using database, he was only storing datas in an arraylist or sth at runtime.
I tried to make a database connection and then a simple query, and it works fine when I'm running it as a Java Application, but as soon as I try to use it inside my web-application, it cannot connect to my DB and throws an exception.
The exception:
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context
with path [/restapi] threw exception [java.lang.IllegalStateException:
Cannot connect the database!] with root cause
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/restapi?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
Here is my code, which works as a Java Application, but not in a webapp:
public class AuthService {
private String url = "jdbc:mysql://localhost:3306/restapi?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try (Connection conn = DriverManager.getConnection(url, "blabla", "blabla")) {
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM users";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String login = rs.getString("login");
String first = rs.getString("firstname");
String last = rs.getString("lastname");
users.add(new User(id, login, first, last));
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return users;
}
Probably this won't be the correct way to connect to a DB (since I probably don't want to connect to the DB on every query), but it's not that important for me NOW.
(Sorry for my english, thanks for the answers.)
Error message clearly says that it couldn't find the mysql driver in below line of error message:-
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/restapi?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
You need to include the mysql-connector jar in your web-project to make it work. If you are using the Maven, then you need to include below dependency in your code, otherwise download jar manually and put it in your classpath.
<!--Mysql-Connector-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
Also I've created a sample App, which is aims to give the quick-start on how to develop a RESTful java application using java,jersey,mysql,spring and hibernate. please read follow it here https://github.com/amitmbm/rest
This question already has answers here:
What is the purpose of 'Class.forName("MY_JDBC_DRIVER")'?
(4 answers)
Closed 6 years ago.
Somebody can explain to me for what this link: org.apache.derby.jdbc.ClientDriver is necessary.
for example:
public class Demo1 {
public static void main(String[] args) {
String driverName = "org.apache.derby.jdbc.ClientDriver";
try {
// loaded the driver
Class.forName(driverName);
System.out.println("driver loaded");
String url = "jdbc:derby://localhost:1527/db1";
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
It isn't necessary, and hasn't been since Java 6. The JDBC 4.0-only features says (in part)
Autoloading of JDBC drivers. In earlier versions of JDBC, applications had to manually register drivers before requesting Connections. With JDBC 4.0, applications no longer need to issue a Class.forName() on the driver name; instead, the DriverManager will find an appropriate JDBC driver when the application requests a Connection.
In earlier versions of Java, it was required to load (and register) the JDBC driver.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java Connecting to remote MySQL database
I'm trying to connect to MySQL database in Eclipse and Java using the following code:
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "RS";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
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) {
e.printStackTrace();
}
But, I get the following error:
MySQL Connect Example.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at Expertise.main(Expertise.java:57)
You need to add the mysql jdbc driver jar to your classpath.
Download the mysql-connector to a local directory from here http://www.mysql.com/products/connector/
Go to Eclipse and select your project by right clicking on it.
Then a pop-up menu will get displayed. In there look for the item
properties and select it.
The the properties window will appear, look for the item Java
Build-path on the left select it
Then on the right of the window you will see a button with the "add
library" caption. Click on it and Look for the .jar file that you
just downloaded.
Make sure that MySQL jar is on your class-path
Make sure you have the correct import in your class.
This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 7 years ago.
When trying to connect to mysql I always get this error:
java.sql.SQLException: No suitable driver found for localhost test
I already included the mysql-connector.jar in the /WEB-INF/lib in my app. What else do I need to configure to make it work? Do I need to add something in web.xml? I'm not using the appengine.
Here is my code in the server:
package com.mysql.server;
import java.sql.Connection;
import java.sql.DriverManager;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mysql.client.ConnDb;
public class ConnDbImpl extends RemoteServiceServlet implements ConnDb {
public Connection con;
#Override
public String tryConn() {
try{
String host = "localhost";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "pwd";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(host+db, user, pass);
return "Connected to Database";
} catch(Exception ex) {
return ex.toString();
}
}
}
You will get this exception when the JDBC URL is not accepted by any of the loaded JDBC drivers as per the Driver#acceptsURL() method. You actually forgot the JDBC driver specific URI prefix. For the MySQL JDBC driver this is jdbc:mysql://. The full connection URL should look like this:
con = DriverManager.getConnection("jdbc:mysql://localhost/test", user, pass);
See also:
Connector/J documentation - Obtaining a connection
I found another cause for this error message. In my case the user simply had no privilege to the database e.g. to the selected table. Dear driver developers, why do you use such misleading error messages? A lot of people have real trouble with this.
For me, it was forgetting to include the MySQLJDBC Driver in the project libraries. DOH!
This was giving that error:
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/lib_db","root","root");
but when I changed that to:
Connection connection =DriverManager.getConnection("jdbc:mysql://localhost/db_name?"+"user=root&password=root");
error was gone