Jar file won't recognize mysql database - java

I made a swing application in Eclipse and it works and compiles fine in Eclipse. It's connecting to mysql. The problem is when I turned it into a jar file the database won't connect. When the application is supposed to load the information from the db, nothing is happening.
public boolean deleteAttendance(String idno,String eventtitle)
{
int x;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(dbUrl, "","");
String query = "DELETE FROM attendance WHERE id =? AND title = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, idno);
pstmt.setString(2, eventtitle);
x = pstmt.executeUpdate();
if(x != 0)
return true;
else
return false;
}catch(Exception e)
{
System.out.println("Statement Error " + e);
}
return false;
}

Just to check whether it is the problem with your required jars not on the class path
Go to window -> preferences->java->build path->user Libraries. add your jar to new user library. Now create a new java project in eclipse right click on this project and select add libraries and add the library your just added in your eclipse . Also add required libraries for database (if any) to your project. If on running your jar everything is working fine then surely its the problem of you not adding ODBC/JDBC driver to your class path else its a problem with your jar .

You would need to make sure that the ODBC driver is in your classpath.
Eclipse does a good job of making sure that your driver is there (because you have to include your dependency jars or else get errors trying to use them).
But once you leave Eclipse - you have to do it yourself.
Is it in your classpath?

To fix this problem, go to artifact and add ojdbc.jar and click OK.
If true then nothing, if not then re-create the jar file.
note:Just make sure ojdbc.jar is added.

Related

How to fix java.sql.SQLException. No suitable driver for jdbc [duplicate]

This question already has answers here:
Getting the following error - No suitable driver found for jdbc:postgresql://localhost: 5432/testDBMS
(4 answers)
Closed 3 years ago.
I'm getting an error java.sql.SQLException No suitable driver for jdbc:derby:books when I try to run a file from command line. In Eclipse, everything works fine. I read a book "Java, How To Program" Deitel&Deitel and the file is an example from it. When I try to compile program from command line it shows no error, but the problem is with running. Please help
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";
String user="deitel";
String password="deitel";
try (
Connection connection = DriverManager.getConnection(
DATABASE_URL, user,password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.printf("Table Authors database books:%n%n");
for (int i = 1; i <= numberOfColumns; i++) {
System.out.printf("%-8s\t", metaData.getColumnName(i));
}
System.out.println();
while (resultSet.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
System.out.printf("%-8s\t", resultSet.getObject(i));
}
System.out.println();
}
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
Command line execution:
javac DisplayAuthors.java
java DisplayAuthors
You are running in the command line your class file without the dependencies.
In your eclipse IDE you maybe have a derby.jar or similar dependencies and eclipse adds all automatically to the execution. Is required to add all the dependencies when you are executing directly from the command line.
If you are note creating a runnable jar with dependencies in MANIFEST.MF and you are trying to execute the class directly is required to add the -cp parameter with the path to all the dependencies:
Example:
java -cp Derby.jar;. DisplayAuthors
Summing that the Derby.jar and your class are in the same place and there is no more dependencies to add.
More information about:
Java Command line (Oracle Java9 SE)
Differences between "java -cp" and "java -jar"?
java.sql.SQLException. No suitable driver for jdbc
The above error jumps when JDBC DriverManager can't find any suitable driver for the given connection URL. Either the JDBC driver isn't loaded at all before connecting the DB, or the connection URL is wrong.
The URL should be like this,
jdbc:derby://localhost:1527/dbname;create=true;
or
jdbc:derby:books;create=true;
Use create=true if you want the database to be created if it doesn't exist.
And finally, check that Derby JAR file is on the classpath. If you can't find it, then you can download the JAR from here and add to the project Library folder.
For Apache Derby, the driver class name is org.apache.derby.jdbc.ClientDriver. So put that as follows,
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection connection = DriverManager.getConnection(DATABASE_URL, user, password);
Make sure your URL, username and the password is correct, and try to run your code.

JDBC cannot be resolved to a variable in Eclipse

Currently trying to use a sqlite-dbc4-3.8.2-SNAPSHOT.jar that was given to me as part of an assignment. I've tried running my main file and I get the errors below:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
org.sqlite.JDBC cannot be resolved to a variable
at DbBasic.open(DbBasic.java:54)
at DbBasic.<init>(DbBasic.java:67)
at DbUser.<init>(DbUser.java:40)
at Main.go(Main.java:12)
at Main.main(Main.java:65)
Here's part of the DbBasic class that attempts to connect and open a database using JDBC:
private Connection getConnection()
// get the connection
{
Connection con = null;
try {
con = DriverManager.getConnection(SQLITE_DATABASE_LOCATION+dbName);
con.setAutoCommit(false);
}
catch (SQLException sqle)
{
notify("Db.getConnection database location ["+SQLITE_DATABASE_LOCATION+"] db name["+dbName+"]", sqle);
};
return con;
} // end of method "getConnection"
private void open()
// "open" the database : actually really setting up the connection and obtaining the metadata about the server
// makes sure that database file is present before trying to establish connection
// otherwise SQLite will create a new, empty database with the name provided
{
File dbf = new File(dbName);
if (dbf.exists() == false)
{
System.out.println("SQLite database file ["+dbName+"] does not exist");
System.exit(0);
};
try {
Class.forName(org.sqlite.JDBC);
con = getConnection();
} catch ( ClassNotFoundException cnfe ) {
notify("Db.Open",cnfe);
};
if (debug) System.out.println("Db.Open : leaving");
} // end of constructor "Open"
I have already tried adding external JAR's and the .jar file is then added to my 'Referenced Libraries' in Eclipse.
I'm having trouble understanding the Class.forName(org.sqlite.JDBC) and how to make it work with my .jar file
Though the post is relatively old and the OP might not be interested in a solution for this issue now anymore, thought of putting this as an answer. It might help someone who runs into such silly issues. This is one of the common mistakes that people do while using Eclipse as an IDE, try to run code that doesn't even compile.
You can check the "Problems" view in Eclipse and fix the compilation errors and then try to compile your program. The obvious error here on this question is the missing double quotes "" while using the driver name.
Class.forName("org.sqlite.JDBC");

How do I create a H2 database inside a java project in Eclipse?

I want to create an embedded H2 database in my simple java project in Eclipse. How do I do this programatically and package the db inside my code ? I tried a SO post for this
and got an error in my code.
Code -
public static void main(String[]args){
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:˜/test");
ds.setUser("sa");
ds.setPassword("sa");
try {
Connection conn = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
Error -
org.h2.jdbc.JdbcSQLException: A file path that is implicitly relative to the
current working directory is not allowed in the database URL "jdbc:h2:˜/test".
Use an absolute path, ~/name, ./name, or the baseDir setting instead. [90011-181]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.engine.ConnectionInfo.getName(ConnectionInfo.java:398)
at org.h2.engine.Engine.openSession(Engine.java:45)
at org.h2.engine.Engine.openSession(Engine.java:167)
at org.h2.engine.Engine.createSessionAndValidate(Engine.java:145)
at org.h2.engine.Engine.createSession(Engine.java:128)
at org.h2.engine.Engine.createSession(Engine.java:26)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:347)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:108)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:92)
at org.h2.Driver.connect(Driver.java:72)
at org.h2.jdbcx.JdbcDataSource.getJdbcConnection(JdbcDataSource.java:190)
at org.h2.jdbcx.JdbcDataSource.getConnection(JdbcDataSource.java:161)
at MyCode.main(MyCode.java:8)
I saw this link - https://groups.google.com/forum/#!msg/h2-database/SlSwte0DLSU/eWj0UaejdkEJ and Where are my H2 database files?. Its not clear how I can get the exact path to test database on my windows pc.
How do I first access the test database and then create another database inside my java project ?
Thank you.
You have used the wrong character. You need to use ~ (tilde) and you have use ˜ (I don't know what it is, but it's not a tilde).
The location of the H2 files is very nicely documented. To view the contents, execute the h2.jar. It is not only the driver, but also an executable that will start a web-based applications for DB management.

Unable to add odbc5.jar in classpath

I want to connect to the oracle DB using Play Framework 1.2.5. FOr this I have modified the application.conf file as follows:
db.url=jdbc:oracle:thin:#localhost:1521/orcl
db.driver=oracle.jdbc.OracleDriver
db.user=system
db.pass=tiger
Then I tried to add the driver i.e. classes12.jar/odbc5.jar but everytime when i try to run it, I am getting the exception:
Cannot connect to the database, Driver not found
For adding the jar file in Eclipse IDE, below are the steps I tried:
1) Added it in the lib folder (present under the root directory of my new application) and then added it to the java build path
2) Added it in the framework/lib folder (inside the downloaded framework folder) and then added it to the java build path
In both the cases, I am getting the above mentioned exception.
Also, Please list down the steps for connection to an oracle db, I am not able to find it anywhere in the documentation
EDIT
I am able to add the jar in the classpath, everything was fine except that I did not restarted the server once it failed to connect the jar.
I did this code for fetching some data from the database:
Connection conn = DB.getConnection();
PreparedStatement stmt = null;
System.out.println(conn);
try {
stmt = conn.prepareStatement("select dept_id from emp where emp_id = 11");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("Dept Id: " + rs.getInt("dept_id"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This approach is working but I am having a confusion:
If I comment the entire block of code and run the application then I can see the message in the console stating the connection is made to the DB. Hence :
1) Is the above block of code the right approach to fetch the data from Oracle DB or something better than this is present?
2) Is it like for the entire application lifetime, the connection with tht DB will persist?
I am a newbie in this, hence struggling :(
Please let me know hoe to proceed with this.
Regards
Oracle db driver class name is oracle.jdbc.driver.OracleDriver

Get mysql and java to work together

I have Eclipse Indigo on Mac Os X and I have downloaded mysql connector (version 5.1).
I have added the jar to the project and I am using this code:
public class Test
{
public static void main (String[] args)
{
try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {
String lastName = rs.getString("Lname");
System.out.println(lastName);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
When I try to execute the program I get this exception:
Got an exception!
No suitable driver found for jdbc:msql://200.210.220.1:1114/Demo
My question is : how to install the driver? What else should I do?
And once installed the driver, how do I get my database URL (I am using mysql 5.5)?
I haven't found a valid guide on the web, they're all too specific.
Your JDBC connection URL is not correct, refer to the official documentation to check the required format for the URL .
In your case the URL will become :
String url = "jdbc:mysql://200.210.220.1:1114/Demo";
you're missing the "y" in jdbc:mysql
You are using MySQL, the URL should look like this:
jdbc:mysql://200.210.220.1:1114/Demo
may be, review the IP and PORT.
You may have added the jar to your project but have you also added it to the project classpath? Having the jar exist as a file in your project won't solve the problem. The jar file is clearly not accessible to your program. Right click on your project -> Build Path -> add the jar there.
Database URL looks ok, assuming you have the right host address and port number.

Categories

Resources