I have been starting off with some JDBC a few days ago as of 2019/3. And there was this error occurring when I try to comply the code below in my eclipse IDE.
I actually did some research before this and I have tried:-
-Adding external libraries from the project menu
-Reinstalling and trying out different ides(thinking it was just eclipse but turns out its something about my system)
-reinstalled both jdk and the jdbc connector
and still, the problem persists.
import java.sql.*;
public class Driver{
public static void main(String[]args)throws Exception {
String url = "jdbc:mysql://localhost:3306/main";
String uName = "Ng Jun Han";
String pW = "password";
String query = "SELECT first FROM students WHERE id = 1";
Class.forName("com.sql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uName, pW);
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
rs.next();
String name = rs.getString("first");
System.out.print(name);
st.close();
con.close();
}
}
This is how my project directory looks like
My biggest concern regarding the topic is about something wrong I did with the installation methods. Mainly because there are not much up-to-date resources to follow.If so, does anyone know the CORRECT way of fixing it?(the driver jar file is located at C:\Program Files\MySQL , and i c/p-ed it into my the libraries file in my project directory) Thanks for helping:)
Try this class name :
Class.forName("com.mysql.cj.jdbc.Driver")
Refer to the official docs
Related
This question already has answers here:
How do I resolve ClassNotFoundException?
(28 answers)
Closed 2 years ago.
This is the code I've written:
package JDBC;
import java.sql.*;
public class JDBC {
public static void main(String[] args) {
try{
String driverName = "org.apache.derby.jdbc.ClientDriver";
String dbURL = "jdbc:derby://localhost:1527/Student";
String dbUser = "DV";
String dbPass = "Pass";
Class.forName(driverName);
Connection con = DriverManager.getConnection(dbURL, dbUser, dbPass);
Statement stmt = con.createStatement();
String sql;
sql = "create table Student(Enroll_No Varchar(20), Name Varchar(20), Gender Char, Age Int, CGPA Float, Email_ID Varchar(30))";
stmt.executeUpdate(sql);
stmt.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
The error I'm getting is:
run:
java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver
BUILD SUCCESSFUL (total time: 0 seconds)
and no table is created. I'm using Glassfish 4.1.1(Derby Database) on NetBeans IDE 8.2
For a ClassNotFoundException, you might want to check about missing .jar files in your project library.
Go to your Project Folder on Netbeans (top left corner), then Libraries and then check for "derbyclient.jar" and "derby.jar" files.
If they are not present, add them manually from your GlassFish folder.
Right click on Libraries -> Add JAR/Folder... Browse to your Glassfish 4.1.1 installation folder -> javadb -> lib and select derbyclient.jar and derby.jar files.
This should work and the exception shall be removed.
I am following Java: How To Program - Chapter 24. The chapter deals with database implementation in Java. I followed the steps to setup "Derby", but I get the error java.sql.SQLException: Database 'books' not found..
I checked $PATH to make sure it includes $DERBY_HOME. $DERBY_HOME points to the correct folder(/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home/db).
I checked $JAVA_HOME and it was also setup correctly(/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home).
I can use the tool ij and it shows me the database that is setup. I added derby.jar to the package in eclipse. The following is the code from the book, but when I compile it I get the error java.sql.SQLException: Database 'books' not found.
I looked it up online, and there were recommendations that I add //localhost:1527/books. But if I add that I get the java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/books error.
There was also suggestions that I use Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();, that didn't solve the problem either.
I have copy/pasted the books.sql database in the same package as the one that contains the source code.
Does anybody know how to solve the problem? I am running MacOS Sierra.
public class DisplayAuthors {
public static void main(String [] args) {
final String DATABASE_URL = "jdbc:derby:books";
final String SELECT_QUERY = "Select authorID, firstName, lastName from authors";
try(
Connection connection = DriverManager.getConnection(
DATABASE_URL, "deitel", "deitel");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_QUERY)){
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfCols = metaData.getColumnCount();
System.out.printf("Authors of table of Books databse:%n%n");
for(int i = 0; i < numberOfCols; i++)
System.out.printf("%-8s\t",metaData.getColumnName(i));
System.out.println();
while(resultSet.next()){
for (int i = 1; i <= numberOfCols; i++)
System.out.printf("%-8s\t",resultSet.getObject(i));
System.out.println();
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
I figured the problem was. When the creating the database via ij I had to be in the same directory that the source file is. Now under eclipse I thought that this would mean I need to be under package folder(JAVAProject/src/package), but that was wrong. I had to be under (JAVAProject).
I'm fairly new to database management. I'm just trying to connect to the database and retrieve and display a table in the command prompt. The database is not on my computer. I am fairly certain that the url is the problem. The code:
import java.io.*;
import java.sql.*;
class transfer{
//driver and DB URLs
final static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
final static String DB_SQL = "jdbc:microsoft:sqlserver://localhost:1433;" + "database=DataDB;" + "user=sa;" + "password=1234";
//Database Username and password
final static String user1 = "sa";
final static String pass1 = "1234";
static ResultSet rs;
public static void main(String args[]) throws SQLException, ClassNotFoundException{
Connection conn_sql = null;
Statement stmt_sql = null;
//Statement stmt_ora = null;
//Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Open Connection
System.out.println("Connecting to SQL database...");
conn_sql = DriverManager.getConnection(DB_SQL, user1, pass1);
//Execute Query
String sql_query;
System.out.println("Creating statement for SQL...");
stmt_sql = conn_sql.createStatement();
sql_query = "Select * from attendancesummary";
rs = stmt_sql.executeQuery(sql_query);
System.out.println("SQL table details");
System.out.println("Creating statement for SQL...");
while(rs.next()){
//Retrieve data
int cno = rs.getInt("CardNo");
int in_time = rs.getInt("entry");
int out_time = rs.getInt("Exittm");
String name = rs.getString("Name");
int date = rs.getInt("TrDate");
//Display data
System.out.print("Employee ID: "+cno);
System.out.print("\tName: "+name);
System.out.print("\tDate:"+date);
System.out.print("\tEntry: "+in_time);
System.out.print("\tExit: "+out_time);
}
}
}
The database name is DataDB and the table that I want to retrieve and display is attendancesummary. I have set my path as "C:\Program Files\Java\jdk1.8.0_11\bin";"C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar"
The code compiles fine.. but when I run it, I get the following error:
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run
at java.net.URLClassLoader$1.run
at java.security.AccessController.doPrivileged
at java.net.URLClassLoader.findClass
at java.lang.ClassLoader.loadClass
at sun.misc.Launcher$AppClassLoader.loadClass
at java.lang.ClassLoader.loadClass
at java.lang.Class.forname0
at java.lang.Class.forname
at transfer.main
I am truly lost. Any help would be appreciated!
It means that sqljdbc4.jar is missing from your CLASSPATH while running the code. If you are running this from command line then add the path to sqljdbc4.jar in -cp switch of java command.
If you are running from eclipse, then add sqljdbc4.jar in your build path.
Add sqljdbc4.jar in your classpath.
If you are using Eclipse then you can right click on project -> properties -> java build path.
Go to libraries and click on add external jar.
Then add the jdbc driver jar.
Hope this helps.
You have to add the JDBC driver to your project class path: example if you are using Eclipse put the jar in the 'lib' folder
Guys,
I know there are some new features in JDBC4.0 and one of them is that you don't need to load database drivers explicitly as the JDBC API will automatically load the driver when you call getConnection(). So I just wanna test it.
BTW, I use Eclipse as my Dev Tool.
Here are my code snippets:
public class Test002JDBCRowSet {
public static void main(String[] args) throws Exception{
String connURL = "jdbc:oracle:thin:#192.168.1.150:1521:";
String database = "bmdw";
String userName = "bmdw";
String passWd = "bmdw";
String driver = "oracle.jdbc.driver.OracleDriver";
String SQLStr = "select t.Empno, t.Ename, t.job, t.sal from employer t where t.sal > 1500";
/*
try{
Class.forName(driver);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
*/
//Latest Method4 : Search for some data with RowSet, offline!
RowSetFactory rsf = RowSetProvider.newFactory();
try(
Connection conn = DriverManager.getConnection(connURL + database,userName,passWd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStr);
CachedRowSet cachedRS = rsf.createCachedRowSet();){
cachedRS.populate(rs);
conn.close();
System.out.println("======Employee List -- Salary more than 1500======");
System.out.printf("%-15s%-15s%-15s%-15s%n","Employee No.","Employee Name","Employee Job","Employee Salary");
try{
while(rs.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
while(cachedRS.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
I got the runtime exception :
java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#192.168.1.150:1521:bmdw
However, if I remove the comments about loading oracle driver explicitly, it works well.
And I'm sure I have already add the ojdbc14.jar into classpath.
So I don't know what happened. I'm trying to figure out how does the method 'getConnection()' works.
I checked System.getProperties() but there is no property named 'jdbc.driver'. Even if I added it and set the value to 'oracle.jdbc.driver.OracleDriver'. It still doesn't work.
I checked ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()) and I found there is only one default file :
jar:file:/D:/Java/jdk1.7.0_03/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
I has so far achieved little.
There might be some oversight in the configuration of Eclipse.
Hope anyone can help me.
Thanks.
I agree with #kordirko and his comment. OP also seems to have confirmed that his problem is resolved because of his comment. Hopefully he gets notification of this and makes it an answer. :)
Check this link: http://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcvers.htm#JJDBC28109 --> You need to have the ojdbc6.jar in your classpath environment variable in order to have JDBC 4.0 standard support. – kordirko
Im trying to establish a connection but having the mentioned error.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cams?zeroDateTimeBehavior=convertToNull", "root", "root");
System.out.println("Connected to Database successfully");
Statement st = conn.createStatement();
s.assignStall(s.numOfStall + 1, stallOwnerId, category, iCanSelected,
contact, name, add, email, unitNo, stallName);
s.showAssignedStall();
/*
int result = st.executeUpdate(
"INSERT INTO StallOwner" (sId, sCat, cant, sContact,
sName, sAdd, sEmail, sUnitNo, sStallName) VALUES(
"")
)
*/
jTextFieldUserId.setText("");
jTextFieldName.setText("");
jTextFieldAddress.setText("");
jTextFieldContact.setText("");
jTextFieldEmail.setText("");
jTextFieldUnitNo.setText("");
jTextFieldStallName.setText("");
} catch (Exception e) {
System.out.println("Error: " + e.toString() + e.getMessage());
}
}
This is my 1st time with JDBC. Please help
Your will need to add the jar file containing the mysql driver to the classpath.
you have forgotten to include the mysql.jar
if you are using ECLIPSE IDE then follow these steps
right click on your project
go to buildpath
click configure build path
click add external jars
give the path to mysql.jar
You are missing mysql jdbc jar(jar containing the class com.mysql.jdbc.Driver) on your classpath. Add the required jar on your classpath.