Unable to add odbc5.jar in classpath - java

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

Related

Java JDBC Driver stops working after initial execution [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
I am currently making a backend reporting system (for a voting system assignment) using Java on VS Code, I am connecting to a MySQL database using the JDBC library in order to do calculations and stats and so on. So what happens is that once I create a project file and include the mysql-connector-java-8.0.25.jar in the referenced libraries, I can connect to the DB and retrieve data from the tables just fine, but after a few executions I no longer get output and it shows me the error "java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver".
Can anyone tell me why this is happening and how to fix this? There are no changes that I know of taking place in the Environment Variables (at least from what I can see in Windows path list) unless something is being overwritten somewhere or that it's a bug of some sort. Any advice would be greatly helpful, I've been unable to figure this out all day
This is what my ReportSystem.java looks like...
import java.sql.*;
public class ReportSystem
{
public static void main(String[] args)
{
//Test driver connection/registration
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ElectionDB","<username>","<password>");
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM ElectionDB.Votes");
int typeColumn = 1;
int districtColumn = 2;
//Output results line by line
while(result.next())
{
System.out.println(result.getString(typeColumn));
System.out.println(result.getString(districtColumn));
}
//Remember to close the connection
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
My file structure as in the directory is as follows:
ReportSystem
>src > ReportSystem.java
> ReportSystem.class
>lib
>.vscode > settings.json
The JRE system library used is: [jdk-16.0.1]
The Referenced Libraries contains: [mysql-connector-java-8.0.25.jar]
Screenshot for context Project Setup in VS Code
I'm able to get result after running code 20 times continuously by clicking the run button. The only difference is the JDBC connection string, which is copied directly by right clicking the MYSQL connection:
So in my project, the connection string is like:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=username","<username>","<password>");
OR
You could try
String url="jdbc:mysql://localhost:3306/ElectionDB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
For your reference, OS Infomation:
MySQL: 8.0 // mysql-connector-java-8.0.25.jar
VSCode: 1.56.2 //
java.home: JDK16 // Debugger for Java: 0.33.1

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.

Jar file won't recognize mysql database

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.

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