"ClassNotFoundException: com.mysql.jdbc.Driver" - java

I’m new using IntelliJ 13 and I have a problem on connection to MySQL. I’m using the code as below and this code I learn from tutorials Manage Your Database Scheme with IntelliJ IDEA 12.
public class App {
public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
public static final String JDBC_URL = "jdbc:mysql://localhost/sample";
public static final String JDBC_USER = "root";
public static final String JDBC_PASSWORD = "";
public static void main (String[] args) throws SQLException, ClassNotFoundException {
Statement statement = null;
try{
Class.forName(JDBC_DRIVER);
Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select id, firstname, lastname, email " +
"from customer");
System.out.println("First name\tLast name\tEmail");
int count = 0;
while (resultSet.next()){
String firstname = resultSet.getString("firstname");
String lastname = resultSet.getString("lastname");
String email = resultSet.getString("email");
System.out.printf("%s\t%s\t%s%n", firstname, lastname, email);
count++;
}
System.out.println("--");
System.out.println(MessageFormat.format("Rows: {0}", count));
} finally {
if(statement != null){
statement.close();
}
}
}
}
I have tried many solution based on this issue on https://stackoverflow.com/ but nothing can solved my problem.
It give error message like this
Connection to MySQL – sample#localhost failed: Exception in thread “main” java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
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:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at com.intellij.persistence.database.console.RemoteJdbcServer.main(RemoteJdbcServer.java:15)
I've followed this as well to solve my problem, but nothing works to me even the problem is same.
http://nixmash.com/java/classnotfoundexception-com-mysql-jdbc-driver-fix-in-intellij-idea/. Actually, I want to create database using MySQL on IntelliJ 13 but the connection to MySQL is failed. I have tried to solve this problem with putting mysql-connector-java-5.1.26-bin.jar in project structure, but it's not work for me. I don't know how to solve this problem? I hope some experts on this issue will help me some ways to solve this problem.
I cannot use the comment, I don't know why. So I reply the answer here. Ashish: I already download the jar files, but I don't know where to put that files. Do you have idea?

You need to download jar containing com.mysql.jdbc.Driver .
So you can Download jar from here and then set your classpath.

Related

Java: ucanaccess hsqldb java.lang.NoSuchMethodError:

I downloaded and installed the uCanAccess jars by following instructions from here:
Manipulating an Access database from Java without ODBC
I'm learning how to use the microsoft access db for java and this is the coding I used
package Main.Net;
import java.sql.*;
public class DataBase {
Connection con;
Statement st;
ResultSet rs;
public DataBase() {
}
private void connect() {
try {
//String driver = "sun.jdbc.odbc.jdbcodbcdriver";
//Class.forName(driver);
String db = "jdbc:ucanaccess://C:/Users/MyUser/workspace/Connectors_DB.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement();
String sql = "select * from Table";
rs = st.executeQuery(sql);
while(rs.next()) {
String username = rs.getString("Username");
String password = rs.getString("Password");
System.out.println(username + "\t" + password);
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DataBase().connect();
}
}
and when I run the java program, it comes with this error
Exception in thread "main" java.lang.NoSuchMethodError: org.hsqldb.DatabaseURL.parseURL(Ljava/lang/String;ZZ)Lorg/hsqldb/persist/HsqlProperties;
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at net.ucanaccess.jdbc.DBReference.getHSQLDBConnection(DBReference.java:354)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:206)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Main.Net.DataBase.connect(DataBase.java:23)
at Main.Net.DataBase.main(DataBase.java:42)
error is at this code:
String db = "jdbc:ucanaccess://C:/Users/MyUser/workspace/Connectors_DB.accdb";
con = DriverManager.getConnection(db);
does it have something to do with the version of the hsqldb? because if it does I already tried downloading other versions of hsqldb and the same error appears
here are the jars I'm using:
ucanaccess-2.0.9.3.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.8.jar
so... how can I fix this?
The answers in this thread suggest, that there are multiple hsqldb-versions on your classpath. Maybe one of the other involved jars contains hsqldb as well? You can inspect them using a zip tool of your choice, or the command jar -tf foo.jar.

Connecting a Java application to an SQL database with Eclipse

I know this has been asked before but I really can't get this to work and as far as I can see I've followed all the steps.
I'm using Eclipse.
So I downloaded the Microsoft SQL Driver sqljdbc v4.0.
I created a new project and class. I edited the build path by adding the .jar file to the libraries.
I typed the following code:
package com.test.sql;
import java.sql.*;
public class Connect
{
public static void main (String[]args)
{
Connection con = null;
String conURL = "jdbc:sqlserver://localhost; databaseName=AnotherTestDB;";
try
{
con = DriverManager.getConnection(conURL);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I got the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost; databaseName=AnotherTestDB;
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.sql.Connect.main(Connect.java:11)
A bit more research and I was told put it in the java /lib/ext and reference it from there.
Nothing changed.
Any help?
Thanks.
Normally you need to register the driver before accessing to it:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Try with something like this:
String DRIVER = “oracle.jdbc.driver.OracleDriver”;
String DBURL = “jdbc:oracle:thin:#jiplc0.si.ehu.es:1512:Erreala”;
String UID = “USERNAME”;
String PWD = “PASSWORD”;
Driver kontrolatzailea = (Driver) (Class.forName(DRIVER).newInstance());
DriverManager.registerDriver(kontrolatzailea);
DefaultContext test = new DefaultContext(DBURL, UID, PWD, false);
DefaultContext.setDefaultContext(test);
Thanks for the responses.
I had both the sqljdbc4.jar and sqljdbc.jar referenced. The version of Java I am using requires that I use sqljdbc4.jar but it was being overwritten by sqljdbc.jar so I removed it.
I also changed my code to this:
public static void main (String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://nameMyLaptop//SQLEXPRESS";
Connection con = DriverManager.getConnection(connectionUrl);
}
//Insert catches
}
Apparently I didn't have to change the code but its not giving me that error now. I'm getting a new one but that's unrelated to my question.
Thanks for your time and responses.
You have to add the SQL JDBC Driver in your project libraries. download jtds.jar and add to your libraries. And follow the code below.
public static void main (String[] args) throws Exception{
Connection conn=null;
String url="jdbc:jtds:sqlserver://YourServerIp:1433/dbName";
String username="sa";
String password="****";
String driver="net.sourceforge.jtds.jdbc.Driver";
// Step 1: Load the JDBC driver.
Class.forName(driver);
// Step 2: Establish the connection to the database.
conn= DriverManager.getConnection(url, username,
password);
}
Here you have to follow two steps......

Simple Java web service issue

I want to create a webservice in Java that accesses a database stored in an external server. I have created a BeepWebService class containing the main information:
#WebService
public class BeepWebService {
private Connection conn = null;
private String url = "jdbc:mysql://xxxxxx.ipagemysql.com/";
private String dbName = "beep";
private String userName = "beep_user_name";
private String password = "pswrd";
private String db_str = " select Name beep.SW where Name = ";
public BeepWebService(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
}catch (Exception e) {
System.out.print("failed");
}
}
#WebMethod
public String returnFormat(#WebParam(name="input_value") String input){
String str = null;
String query = db_str+input;
try {
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
str = rs.getString(2);
System.out.println(str);
}
rs.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
}
I have then created the publisher class, named BeepWebServicePublisher:
public class BeepWebServicePublisher {
public static void main(String[] args){
System.out.println("Web Service initiating...");
Endpoint.publish("http://xxxxxx.ipagemysql.com/", new BeepWebService());
}
}
Unfortunately after compiling successfully the two classes and run the application, the output message is 'failed' (meaning that the connection couldn't be estabilished with the database) followed by an exception error. This is the complete output:
Web Service starting..
failedException in thread "main" com.sun.xml.internal.ws.server.ServerRtException: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.HttpEndpoint.publish(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at com.BeepServicePackage.server.BeepWebServicePublisher.main(BeepWebServicePublisher.java:17)
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at sun.net.httpserver.ServerImpl.<init>(Unknown Source)
at sun.net.httpserver.HttpServerImpl.<init>(Unknown Source)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(Unknown Source)
at com.sun.net.httpserver.HttpServer.create(Unknown Source)
... 6 more
As I am a novice in this field, can someone tell me if there is something wrong in the code or the problem may be with the server? Thanks!
Print out the entire stack trace; it'll give you more information than your "failed" message.
Where did you register the MySQL JDBC driver? I don't see it.
UPDATE: I'd recommend that you decompose the problem. Don't put the database code in the web service. Create an interface-based POJO that you can test off line. Get it working, then give an instance to the web service to use.
You have 99 problems, son. Start by fixing one at a time.
This is wrong:
private String db_str = " select Name beep.SW where Name = ";
You need a binding parameter:
private String db_str = " select Name beep.SW where Name = ?";
You need a PreparedStatement, not a Statement.
Then you want to bind the name you pass in.
You only have one column returned by the SELECT; why do you setString on column 2?
Wrong in so many ways.

Java SQl Server connection error

I have written sql server connection part.When I run this code, i got this error.
Error Trace in getConnection() : com.microsoft.jdbc.sqlserver.SQLServerDriver
Error: No active Connection
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sample.DB.getConnection(DB.java:30)
at com.sample.DB.displayDbProperties(DB.java:49)
at com.sample.DB.main(DB.java:85)
I have installed sql sever 2008 R2. I serached google I couldn't find the solution....
This is my code
public class DB {
private java.sql.Connection con = null;
private final String url = "jdbc:microsoft:sqlserver://";
private final String serverName= "localhost";
private final String portNumber = "1433";
private final String databaseName= "XONTHOMass_User";
private final String userName = "sa";
private final String password = "xont#123";
// Informs the driver to use server a side-cursor,
// which permits more than one active statement
// on a connection.
private final String selectMethod = "cursor";
private String getConnectionUrl(){
return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
}
private java.sql.Connection getConnection(){
try{
System.out.println("========1========");
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("==== 2=====");
con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
/*
Display the driver properties, database details
*/
public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}
private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
DB myDbTest = new DB();
myDbTest.displayDbProperties();
}
}
Please help me..I did this application using the eclipse.I have put jar file also `sqljdbc4.jar'...
Please help me
You receive the exception:
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
That means your program cannot find the Driver and therefore not even try to connect to the database.
Mircosoft has an article on How to Get Started with Microsoft JDBC:
The Microsoft SQL Server 2000 driver for JDBC .jar files must be listed in your CLASSPATH variable. The CLASSPATH variable is the search string that Java Virtual Machine (JVM) uses to locate the JDBC drivers on your computer..
As a complete guess, you have installed Express Edition (you should always mention the edition, not just the version) but you have not enabled TCP/IP support using the SQL Server Configuration Manager. By default, Express Edition does not have any network protocols enabled, so connecting over TCP/IP will not work unless you enable it first.
I think this is the driver that you need to use
com.microsoft.sqlserver.jdbc.SQLServerDriver
not com.microsoft.jdbc.sqlserver.SQLServerDriver
Just do one thing go to http://www.java2s.com/Code/Jar/s/Downloadsqljdbcjar.htm and download the sqljdbc jar and use it in your program.

Using MySQL and database and having ClassNotFoundException

I have these two classes in my database package:(DBManager and TaskManager class)
and I create a new object in my main frame which is in the other package and I also imported the database package for my main frame and I call addBirth() on my object,and I want to insert these arguments in my table="birthsql" in MySQL but I found this exception and also was written "SERVER = NULL".
creating an object--> TaskManager tm = new TaskManager();
calling addBirth() method on my object-->, tm.addBirth(3, "Neda","Rahmani", "Mansour", "Sima","December","Tehran");
My TaskManager class:
public class TaskManager {
private int BirthID = 2;
Logger logger = Logger.getLogger(this.getClass().getName());
private Connection conn = DBManager.getConnection();
public int getID()
{
return BirthID++;
}
public void addBirth(int BirthID, String name, String family, String fatherName, String motherName, String DateOfBirth, String PlaceOfBirth) {
try {
Statement stm = conn.createStatement();
stm.executeUpdate("INSERT INTO birthsql (name," + "family," + "fatherName," + "motherName," + "DateOfBirth, " + "PlaceOfBirth)" + "VALUES (" + BirthID + ", '" + name + "', '" + family + "', '" + fatherName + "', '" + DateOfBirth + "', '" + PlaceOfBirth + "')");
} catch (SQLException ex) {
Logger.getLogger(TaskManager.class.getName()).log(Level.SEVERE, null, ex);
}
}}
My DBManager class:
public class DBManager {
private static Logger log = Logger.getLogger(DBManager.class.getName());
private static Connection connection = null;
private final static String DB_URL = "jdbc:mysql://localhost:3306/assignment_2";
private final static String DB_USERID = "root";
private final static String DB_PASSWORD = "123";
public static Connection getConnection()
{
if (connection == null)
{
try {
/* Your code here */
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL, DB_USERID, DB_PASSWORD);
} catch (SQLException ex) {
Logger.Dec 10, 2009 6:44:05 AM database.DBManager getConnection
} catch (ClassNotFoundException ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
return connection;
}}
Stacktrace:
Dec 10, 2009 6:44:05 AM database.DBManager getConnection
SEVERE: null
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at database.DBManager.getConnection(DBManager.java:32)
at database.TaskManager.<init>(TaskManager.java:21)
at adminFrame.AdminFrame.<init>(AdminFrame.java:29)
at adminFrame.AdminFrame$4.run(AdminFrame.java:239)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at database.TaskManager.addBirth(TaskManager.java:30)
at adminFrame.AdminFrame.<init>(AdminFrame.java:46)
at adminFrame.AdminFrame$4.run(AdminFrame.java:239)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121
Just because your code compiles and can start running does not mean you have all the required stuff on your classpath. The code compiles because you're using the basic JDBC interfaces that are built into the Java language distribution, but when you run, JDBC tries to instantiate the MySQL specific connectors and can't (the Class.forName call). It looks like you've got a jar missing on your classpath. You can get one here:
http://dev.mysql.com/downloads/connector/j/5.1.html
I added Driver jar on my classpath
You thought you did it properly, but the JVM is telling you that you did not.
How did you do it? The right way is not a CLASSPATH environment variable. The JVM, IDEs and app servers all ignore it.
The right thing to do depends on how you're running your app.
If you're running on the command line, use the -cp option and provide the full path to the MySQL Connector-J JAR.
If you're using an IDE like IntelliJ or Eclipse, you'll have to know how to add the MySQL driver JAR to the build lib path.
If you're creating a web app, you should either put it in your app's WEB-INF/lib directory or, better yet, the /lib directory for your app server.
Most of all, believe the error message. You did it incorrectly. Figure out the right way.
UPDATE: Looks like a duplicate of 1878405.
Do you have the MySQL JDBC driver jar on your classpath?
If you have the MySQL JARs, make sure they're in the classpath. If you don't, download them here.
You can't write Java without knowing how to set CLASSPATH.
If you're using an IDE like IntelliJ or Eclipse, you'll have to add the JAR to your build library path.
If you're using an app server, you should put it in your WEB-INF/lib or, better yet, the /lib directory for your app server.

Categories