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");
Related
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
Using class.ForName to load ucanaccess in a maven project
OK so I am now totally out of my depth. Everything was going so well before I started to use Maven and now its so much more complicated.
Anyway I am trying to connect to a database using ucanaccess.
public Statement ConnectorNoInsert(String HospNum,String SName,String FName,String DOB) throws SQLException{
Preferences userPrefs = Preferences.userNodeForPackage(main.java.Console.TBB_SQLBuilder.class);
String connectDB ="jdbc:ucanaccess://"+userPrefs.get("PathForDB", null);
System.out.println("Connection To Database Made "+userPrefs.get("PathForDB", null));
Connection conn=DriverManager.getConnection(connectDB);
Statement st =conn.createStatement();
return st;
The error that I get is:
ERROR: java.sql.SQLException: No suitable driver found for jdbc:ucanaccess://PhysJava/Physiology.mdb
so I added Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); above the Connection conn line. This gives me the error:
unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown and the project doesnt compile
I suppose the question is: how to call Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); in a maven project. If I need to use a ClassLoader could someone please show me how
The first one ("No suitable driver") is a run-time error, the second one ("unreported exception") a compile-time one. The error message is pretty explicit: "...must be caught or declared to be thrown..." Fix the code in this sense.
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.
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
I have downloaded the following:
mysql-essential-5.1.65-win32 from this MySQL Dev link
MySQL Connector mysql-connector-java-5.1.21.zip from this link
Now I have started programming with Eclipse. I have made simple java class like below,
public class MySQLAccess {
private static Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args){
try{
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
}catch (Exception e) {
// TODO: handle exception
System.out.println("Error : "+e);
}
}
}
I have also made a folder "lib" in my Java project and I have put that mysql-connector jar over there. But when I run this program it can't find mysql I get the following error in the console :
Erro : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Can someone please tell me where I have made the mistake? Thank you
Putting the full jar-file path in your classpath and restarting cmd (if you are running from cmd) should work-
See here- java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
If it your java application project then you put jar file into jdk library path ext folder.
eg:
C:\Program Files\Java\jdk1.6.0_13\jre\lib\ext
you will get path from your project class path .