This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 2 years ago.
When I run my code, I get this error: Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver; with a stack trace link to line 13 (Highlighted in the code)
I have just started using JDBC and don't know much about it, but I'll go through what I have done so far to get to where I am. As a preliminary, I am using MySQL Workbench and Apache Netbeans 11:
1) Downloaded the .jar connector file
2) Could not find the build path on netbeans 11 and did some research and couldn't find any resources linking to it, so instead used the Driver dropdown through the databases section on the services tab. Now I can see all my SQL databases and tables in my netbeans IDE.
3) Wrote the following code using the 7 steps to connect to the database, establish a connection etc
import java.sql.*;
public class GroundControlToMajorTom {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306//customers";
String uname = "root";
String pass = "";
String query = "SELECT customer_id FROM customers WHERE customer_id = 1";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String id = rs.getString("customer_id");
System.out.println(id);
st.close();
con.close();
}
}
4) Run the code and get a ClassNotFoundException. I did a bit of research and it seems to say that I don't have the connection to the actual driver, but I added it in the drivers section of the services for my project?
Any help would be much appreciated my dudes <3
Add com.mysql.jdbc.Driver to CLASSPATH.
If you use maven, add to <dependencies> section of pom.xml the dependency of required driver (mysql-connector-java):
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
for gradle
compile group: 'mysql', name: 'mysql-connector-java', version: mysqlVersion
You need to add the downloaded JAR to the classpath.
Try this instruction:
Open NetBeans and right-click on the project name in the Projects tab.
Select Properties.
Select Libraries.
Click the Add Jar/Folder button.
Navigate to the directory where the downloaded JAR files are.
Related
This question already has answers here:
Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0
(11 answers)
Closed 6 years ago.
How do I install MSSQL driver in my project with Eclipse's maven? (m2e)? And also make it not conflict with Vaadin? When I install the MSSQL driver locally following these instructions, during the compile and runtime, it says "Could not find archetype from Vaadin-addons."
I have the code:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://server;databaseName=dbname;user=username;password=password");
String sql = "Select * from Table1";
stmt = con.createStatement( );
rs = stmt.executeQuery(sql);
while (rs.next()){
contractorsList.addBean(new Contractor(rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6)));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}finally{
try { con.close(); } catch (SQLException e) {}
try { rs.close(); } catch (SQLException e) {}
try { stmt.close(); } catch (SQLException e) {}
I'm getting the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:450)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:403)
at java.lang.Class.forName0(Native Method)
Which means that it can't find my driver, I think. So I'm following this tutorial on installing the MS SQL driver. I download the driver from microsoft and then I unzip it here:
C:\SQLDriver
In Eclipse, on my project folder, I right click > Debug As > Debug Configurations >
mvn install:install-file -Dfile=C:\SQLDriver\sqljdbc_4.0\enu\sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0.2206.100 -Dpackaging=jar
Then I add in the following in my POM
<properties>
<!–….other versions–>
<sqlserver.version>4.0.2206.100</sqlserver.version>
</properties>
...
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>${sqlserver.version}</version>
</dependency>
I get an error that it can't find my dependency, So I look up the question here, and I found out that I simply need to add sqljdbc4 to my classpath.
I have no idea what that means but google took me here So I attempt to follow the instructions.
In System Properties > Advanced > Environment Variable under Variables, I add the following:
I searched here and it looks like someone else asked the same question
I honestly don't know what people mean by add it to the classpath. Do they mean paste the jars in the same folder as the project? Either way, I just found a .classpath file in my project and added these:
How do I get maven to use this microsoft sql driver?
[Edit] When going to Libraries > Maven Dependencies, right click > build path > configure build path, I see this:
Which, when I click, it doesn't let me edit the path of that file. I'm not sure where to edit it.
You will need to download the source code and the java docs for all the maven dependencies. You can do that by right clicking the maven as discussed here:
https://stackoverflow.com/a/22352526/1475228
Then only you can run the code.
Also look here. This is the one that helped mine.
I am super newer in java language. Now i am getting started java.
I am keen interst know about how to connect java with back end.
For that I have been installed oracle 11g express edition and sql developer.
First of all i just confused here, is these two tools are (oracle 11g express edition and sql developer.) enough for connect java with back end.?
And i am using jdk1.8.0_25 and eclipse editor.
If yes, means, what are the further process to achieve?
Already i know little bit about php, i did something connecting database, retrive the data from database..
So what is my goal is, what is the best way to connect backend with java?
Can anyone java expert explain step step by process?
Step 1 : Download Oracle JDBC Drivers
You can download Oracle JDBC drivers from here. Choose the version appropriate for your database version. In this example, I use the Oracle 11g JDBC driver since I connect to Oracle 11g database. There are two versions available for Oracle 11g, ojdbc5.jar (for JDK 1.5) and ojdbc6.jar (for JDK 1.6). Use appropriate version for your Java installation (Oracle now requires online registration for downloading drivers). I use ojdbc6.jar for this tutorial.
Step 2 : Java Program to Connect to Oracle
The following Java program uses Oracle JDBC driver to connect to a running Oracle database instance. You can use this program on any Oracle database as this example uses Oracle’s built-in dummy table DUAL for fetching system date. DUAL enables us to get values such as system date using a normal SQL query.
// Example Java Program - Oracle Database Connectivity
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OracleSample {
public static final String DBURL = "jdbc:oracle:thin:#localhost:1521:XE";
public static final String DBUSER = "system";
public static final String DBPASS = "manager";
public static void main(String[] args) throws SQLException {
// Load Oracle JDBC Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// Connect to Oracle Database
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
Statement statement = con.createStatement();
// Execute a SELECT query on Oracle Dummy DUAL Table. Useful for retrieving system values
// Enables us to retrieve values as if querying from a table
ResultSet rs = statement.executeQuery("SELECT SYSDATE FROM DUAL");
if (rs.next()) {
Date currentDate = rs.getDate(1); // get first column returned
System.out.println("Current Date from Oracle is : "+currentDate);
}
rs.close();
statement.close();
con.close();
}
}
Before you run the program ensure that you change the values for DBURL, DBUSER and DBPASS. DBURL is of the form,
jdbc:oracle:thin:#machinename:1521:databasename
Replace machinename with the name of the machine where oracle is running and replace databasename with service name of the database instance.
See this page for more details on JDBC API.
Step 3 : Add ojdbc.jar to Classpath
In order to compile or run the above program, you need to add ojdbc.jar to the classpath of your program. If you are using IDE such as NetBeans or Eclipse, you can add ojdbc.jar as a dependent library and NetBeans will automatically add it to classpath.
If you are running the above program from command line, copy ojdbc.jar to the folder where the above Java program is located and then compile the file using the following command (this adds ojdbc.jar to classpath),
javac -classpath ./ojdbc6.jar OracleSample.java
Run the Java program using the following command (ojdbc.jar is added to classpath),
java -classpath "./ojdbc6.jar;." OracleSample
Note that when you are running OracleSample, you need both the JDCB jar file and the current folder in the classpath.
I've searched a lot and spent many time trying register JDBC driver.
First, I copied my ojdbc7.jar file (downloaded from Oracle) into directory shown below:
Driver File(s): /Users/Kamil/glassfish4/jdk7/jre/lib/ext/ojdbc7.jar
Driver Class: oracle.jdbc.OracleDriver
// this is copied from Services/Databases/Drivers/ojdbc
Then, I tried following code:
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(myDriver);
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
... and this one:
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
... and with this line instead:
Class.forName("oracle.jdbc.driver.OracleDriver");
I always get ClassNotFoundException :(
Here is code I try to run:
Connection DBconn;
String USER = "root";
String PASS = "root";
System.out.println("Connecting to database...");
DBconn = DriverManager.getConnection("mysql://localhost:3306/RestToolDatabase", USER, PASS);
System.out.println("Creating statement...");
Statement stmt = DBconn.createStatement();
String sql;
sql = "select surname, id, age\n"
+ "from customers \n"
+ "where name = \"maria\" \n"
+ "order by id;";
ResultSet rs = stmt.executeQuery(sql);
I've also read about setting the classpath as described here:
Right-click your Project.
Select Properties.
On the left-hand side click Libraries.
Under Compile tab - click Add Jar/Folder button.
but there is no "Properties/Libraries" option in NetBeans...
I use Maven and there is following dependency added by some library:
<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>14</version>
<type>pom</type>
</dependency>
Maybe there is some workaround, or other way to add it automatically? It SHOULD be simple but I'm unexperienced and wasted many time on this. Please help.
EDIT: Thank you for replies, yes, I use MySQL Server at localhost:3306 [root]. I have MySQL JDBC connector installed here:
/Applications/NetBeans/NetBeans 8.0.app/Contents/Resources/NetBeans/ide/modules/ext/mysql-connector-java-5.1.23-bin.jar
When I go to "Services" --> "Drivers" --> "MySQL (Connector/J driver)" there is Driver Class path exactly as you suggested, so I use Class.forName("com.mysql.jdbc.Driver") now.
I right-clicked on "MySQL (Connector/J driver)" driver and went to "Connect Using..." --> "localhost, port 3306, user, password". And it is connected now, I see new connection. But still I get ClassNotFoundException.
EDIT 2 - this solution worked for me:
I added following to dependencies in pom.xml:
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
</dependency>
... and builded application; the driver was downloaded and installed. As simple as that... I spent many time on this... It works - yeah! :)
You are using an Oracle JDBC driver on a MySQL database, you should use
Class.forName("com.mysql.jdbc.Driver");
Edit: Thanks to the comments from #duffymo and #Mark-Rotteveel who noticed that the URL of the connection is also wrong, the correct connection is:
Connection DBconn;
String USER = "root";
String PASS = "root";
DBconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RestToolDatabase?" + "user="+USER+"&password="+PASS);
Setting the classpath :
Download the JAR JDBC Connector/Driver
Copy file in subfolder of project (ex: libs) (not 'src')
Project->Properties->Libraries->Add Jar/Folder->Select file
And packaging dependent librairies with relative path in 'dist' :
Project->Build->Packaging->Check "Copy Dependent Librairies"
I don't think the JDBC JAR belongs in that directory. The CNF exception backs me up.
I would recommend putting that JAR in your project WEB-INF/lib, repackaging the WAR, and trying again.
This line is correct:
Class.forName("oracle.jdbc.driver.OracleDriver");
The full class name has to match that in the JAR. This is the only one that does.
You have to use the driver that matches your database: Oracle for Oracle, MySQL for MySQL. What database are you using?
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
This worked for me. Since there's no Property and Library in Netbeans apache. Good luck.
This is my first Java application and I'm completely inexperienced with Java and NetBeans.
I have been trying to connect to sql and get some records for 2 days. The problem is about jdbc driver, let me explain. I have downloaded sqljdbc driver and then followed these steps:
Right-click Project->Select Properties->On the left-hand side click Libraries->Under Compile tab - click Add Jar/Folder button and select sqljdbc4.jar file. Then it should be ok, right?
Then I wrote this code But I cant get rid of this exception:
Exception in thread "main" java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SqlServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:30)
This is the code
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:sqlserver://.\\SQLEXPRESS;databaseName=Northwind; Integrated Security = SSPI ";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SqlServerDriver");
con = DriverManager.getConnection(url);
String sql = "Select Top 3 from * person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
According to this page, the class is called SQLServerDriver and not SqlServerDriver. Case is important!
So, try:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Note that with newer versions of JDBC, it's not necessary to load the driver class explicitly with Class.forName(...). The page I linked to explicitly explains that you don't have to do it. So, you can just remove the whole line and then it should work.
Java: JDBC Connectivity with MSSQL in NetBeans
Steps
Download JDBC from:
https://www.microsoft.com/en-in/download/details.aspx?id=11774
Run sqljdbc__enu.exe - unpack this zip file in %Program
Files (x86)% with the default directory: Microsoft JDBC DRIVER
for SQL Server
Create your new project in NetBeans
Right Click on the project - select Properties - select Libraries
from left panel - click Add JAR/Folder button - select your JAR file
and open - ok
Open Sql Server Configuration Manager - select Protocols for
SQLEXPRESS under Sql Server Network Configuration - Right Click on
TCP/IP - select Properties - change Enable to Yes - Click IP
Addresses - Goto IPAll - Change TCP Dynamic Ports to 49169 and TCP
Port to 1433 - Apply - Ok - Restart the Computer
Open Run and type Services.msc - Start SQL Server Browser
Goto project and write code for database connectivity.
Code for Local Database Connectivity:
String url = "jdbc:sqlserver://YOUR PC NAME;instanceName=SQLEXPRESS;DatabaseName=dbname;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection myCon = DriverManager.getConnection(url);
Statement myStmt = myCon.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from table name");
I have an update about this issue.
Go to this link, find your compatible JDBC driver (I dowloaded 6.0 version).
Find the appropriate jar in the file you downloaded (I used jre7\sqljdbc41.jar).
For Intellij Idea press Ctrl+Shift+Alt+S and open Project Structure then in the dependencies section add your jar file.
I hope it works for you too.
This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 3 years ago.
I am working on a web application where I am creating MSSQLSERVER 2008
database dynamically.
But it's giving me
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;databaseName=master
My code is:
String dbName = "db1";
try {
String url = "jdbc:sqlserver://localhost:1433;databaseName=master";
Connection connection = DriverManager.getConnection(
url,
"sa",
"roshan14121987");
Statement statement = connection.createStatement();
String sqlquery = "CREATE Database \"" + dbName + "\"; ";
statement.executeUpdate(sqlquery);
statement.close();
connection.close();
} catch(Exception e) {
e.printStackTrace();
}
I have added sqljdbc4.jar in lib. I have tried it on both NetBeans (with GlassFish and Tomcat Server) and Eclipse IDE(Tomcat Server).
On the other hand I have tried this with simple desktop application, it's working fine on both IDEs. With sqljdbc4.jar added in lib.
Before calling DriverManager.getConnection() you will have to load the SQLServer JDBC driver. You can do Class.forName("xxxx"); where xxxx is the appropriate driver class (fully qualified name with package prefix).
EDIT: Do this Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load the driver. Refer MSDN link for more.
Is sqljdbc4.jar in your war file under WEB-INF/lib. This is the alternate location to $CATALINA_HOME/lib and recommended to keep your web application self-contained. Further, if you should ever need to change servers, you need only drop the war into your webapps directory.
You might also need a Class.forName([database class]).newInstance, but that isn't necessary using a JDBC 4.0 driver. Good luck and if you have further problems, do leave a comment.
The error happen in the runtime on Tomcat Server,right? I think you need to make sure your sqljdbc4.jar deploy the in the Server.