SQLite and Java - java

When I create a new project in Netbeans, I added the sqlite.jar to the classpath and library. I wrote a short test program and it works great!
Now I want to add a GUI as a front end, so I create a brand new project in Netbeans but I create a swing project and create the GUI using netbeans. The GUI works fine by itself (just taking input and writing it to the console as a test).
So now in the GUI project I go and in the "Source Package" folder I add a new java class and I copy/paste the code from my other (working) sqlite implementation. I also add sqlite to the Classpath/library and nothing works!
This is (part) of the code I have:
package my.test;
import java.sql.*;
public class sqlaccess {
Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();
/* commented out the connecting/creating tables etc code */
}
The error I get is this:
C:\Users\xxx\Documents\NetBeansProjects\TestUser\src\my\testuser\sqlaccess.java:12: <identifier> expected
Class.forName ("org.sqlite.JDBC");
C:\Users\xxx\Documents\NetBeansProjects\TestUser\src\my\testuser\sqlaccess.java:12: illegal start of type
Class.forName ("org.sqlite.JDBC");
So I'm pretty sure the problem is the way I combine these 2 classes/files since each one works perfect stand alone.

The problem is this code block:
Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();
You need to move this code into a method, a constructor, a static initializer, or something similar. Code cannot be placed directly into the class body in Java.

How about ..
public class sqlaccess {
void init(){
try{
Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();
/* commented out the connecting/creating tables etc code */
}
catch(ClassNotFoundException ex){
//Handle Exception
}
}
}

Related

Unable to load suitable drive from java 18 on linux 24.02.1 wsl with mysql version 8.0.31 [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
What is a classpath and how do I set it?
(10 answers)
Closed last month.
I get the following error when trying to execute a Java program with SQL code:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost/opiejbc1
I have installed the driver mysql-connector-j-8.0.31.jar in /usr/share/java
I have called the class with java -cp ./:/usr/share/java TestApplication
and with CLASSPATH=./:/usr/share/java set.
My Java code is as follows:
import java.sql.*;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/opiejbc1";
static final String USER = "opiejbc1";
static final String QUERY = "SELECT * FROM Test1";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("Name: " + rs.getInt("Name"));
System.out.print(", Phone: " + rs.getInt("Phone"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I have tried inserting Class.forName("com.mysql.cj.jdbc.Driver"); immediately after the try statement, but then I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token(s), misplaced construct(s)
at TestApplication.main(TestApplication.java:10)
What am I doing wrong?
I have tried all the recommended solutions as far as I know, but I still get those errors.
As noted by #g00se, the real problem is that the JAR file for the Connector/J driver is not on your runtime classpath. So the java runtime cannot find it.
Solution: put the JAR file on the classpath.
Notes:
If you use a -cp option, the CLASSPATH environment variable is ignored.
If you put a directory on the classpath, you are NOT telling the java to put JAR files (in that directory) on the classpath.
If you wanted to put all JAR files in (say) "/usr/share/java" on the classpath, you could use a wildcard entry; e.g. -cp .:/usr/share/java/*.jar. Note that the *.jar is not shell globbing. It needs to be processed by the java command. (In some cases you may need to escape it to prevent globbing.)
You should (IMO) take the time to read the Oracle documentation on how the classpath works.
Adding a Class.forName call is NOT recommended (except by people who don't understand the problem). If the drivers are on the classpath then DriverManager will find them. And if they are not on the classpath, then using Class.forName is going to fail.
But the reason that you got a compilation error was that you were inserting it at the wrong place:
try ( // HERE is the wrong place
Connection conn = DriverManager.getConnection(DB_URL, USER, "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
The try with resources syntax only allows variable declarations with initializers in that context. A Class.forName call is not such a thing.
I haven't checked, but I think that inserting
Class dummy = Class.forName("com.mysql.cj.jdbc.Driver");
at // HERE in the above would make the compiler happier. But DON'T. It is unnecessary. It won't help. See above for the correct solution.

Got error while I'm tried to connect database [duplicate]

This question already has answers here:
What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?
(15 answers)
Closed 6 years ago.
Got error while I'm tried to connect SQL database
using cmd. Here is my program.I use jdk 6 version to compile and run
Thanks in Advance.
import java.io.*;
import java.sql.*;
class Dbs
{
public static void main(String args[]) throws Exception
{
try
{
Connection con = null;
Statement s = null;
ResultSet rs = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String bala = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\\ss.mdb";
con = DriverManager.getConnection(bala,"","");
s = con.createStatement();
rs =s.executeQuery("select * from Table1");
while(rs.next())
{
System.out.println("Name"+rs.getString("name"));
System.out.println("No"+rs.getString("num"));
}
}
catch(Exception e)
{
System.out.print(e);
}
}
}
Error:
Are you in the correct directory ? It seems you are in your jdk directory, where you should be in your program's directory (where your Dbs.class resides).
Also, you missed the public keyword. Here, your Dbs is package local, so it won't be visible outside the package. Depending on where you use it, it may trigger the error.
Try:
public class Dbs {
// code
}
Also,
If you don’t explicitly specify a package, your classes and interfaces end up in an unnamed packaged, also known as the default package. Best practice is not to use the default package for any production code.
more here.
the error says the class you are trying to get is not where it must, check the the jdbc driver is in the correct place ,check if you have your JAVA_PATH set and put a try catch to see if there is another error who is causing that

Java-How Do I Rerefrence Sqlite Database in the Same Folder With My Project Files?

am working on a certain java Management System where am using sqlite as my primary database. Am using netbeans gui builder to work on my project. I have googled and stack overflowed how to reference sqlite database in the same dir with my project files without including full path like c://filepath but nothing promising yet. I don't want to include the full path to my database, I want to use sqlite file from the project files so that everything will work smoothly even after distributing my project...
My Connection Class currently Looks like this;
import java.sql.Connection;
import java.sql.DriverManager;
public class Connect {
private static Connection con = null;
public static Connection connecting(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:programming.sqlite");
JOptionPane.showMessageDialog(null, "Working", null, JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
}
return con;
}
}
However that's seems not to work.. Remember Connection class and database are saved in the same dir...
Please note am avoiding absolute path like c://users/programming.sqlite
Anything to help please???
I think it must work as you shown, but, you can load programming.sqlite as a java.io.File and then put absolute path into jdbc url connection. I mean this:
File temp = new File("programming.sqlite");
String connection = "jdbc:sqlite:" + temp.getAbsolutePath().replace("\\","\\\\");
con = DriverManager.getConnection(connection);
...
If this code doesn't work for you, then your problem must be with programming.sqlite location, because in this case it is not on the same home dir of your java programm.

Unable to open Clearcase raima database.

I am trying to read raima database of Clearcase. The db directory is copied from the vob storage and renamd to vob_db. The location where the vob_db is present, there exists the VOB_DB.java file and dependent dlls and jar file. In fact they were copied from below zip file that contains sample program
[http://raima.com/wp-content/uploads/helloWorldSamples/HelloWorld_JDBC_win64.zip][1]
Below java code ( VOB_DB.java ) is written just to open an close database.
import java.sql.*;
public class VOB_DB {
public static void main (String[] args) throws SQLException {
Connection Conn = DriverManager.getConnection ("jdbc:raima:rdm://local");
Statement Stmt = Conn.createStatement ();
Stmt.execute ("OPEN DATABASE vob_db");
Stmt.close ();
Conn.close ();
}
}
The above code compiles successfully. But when I run it throws below message.
Error: Could not find or load main class JAVA_DB
I am really not sure what wrong is with the program or is there anything missing in it or any dependancy is not set.
I am not going to tell you what to do but directly accessing a ClearCase Raima database is asking for serious trouble. Not something you want to do if your company's intellectual property is stored there.
There are APIs and command line options available for almost anything you would want to do with ClearCase.
Also, the Raima database used for ClearCase is not 100% off-the-shelf. There are a number of additional features which are not documented.

how to link java and mysql

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}
First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done
1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help

Categories