I have a JAR file that doesn't connect to the database even though it connects just fine in the IDE. I'm stuck and I don't know where to go from here. I am using Java 8 in IntelliJ trying to run SQLite.
Here is the code for the Database class.
private static Connection connection = null;
private static boolean connected = false;
static void connect() {
String driver = "org.sqlite.JDBC";
String db = "schedulerDB";
String path = "lib\\";
String url = "jdbc:sqlite:";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url + path + db);
printInfo("Connected to database : " + db);
connected = true;
} catch (SQLException e) {
printError(1100, "Could not connect to database", e);
} catch (ClassNotFoundException e) {
printError(1101, "Driver not found error", e);
}
}
When I run the JAR file in the terminal, I get:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
Please help me.
Added e.printStackTrace(); as requested:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.throwex(DB.java:918)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.jdbc3.JDBC3Statement.execute(JDBC3Statement.java:52)
at scheduler.Database.query(Database.java:337)
at scheduler.User.buildList(User.java:42)
at scheduler.User.<clinit>(User.java:85)
at scheduler.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Change the value of url to
url = "jdbc:sqlite::resource:"
Your exception is actually caused by a MalformedURLException. The reason you are getting this is because lib\schedulerDB is not a valid URL.
URLs must use forward slashes (/), on all systems—even Windows. This is a requirement of the URI specification itself. (A URL is a type of URI, so every URL must conform to the rules of a URI.)
Making your URL valid should do the trick:
String path = "lib/";
Related
I already saw many post where people were trying to add the driver. I'm using intelij as IDE and added the driver under Modules => Dependencies => Add Jar; So my IDE identified the driver and can show me the source file of it. My problem is, as soon i start my server I'll get that error that he couldn't find the driver:
My Code:
private void createDB()
{
try {
Class.forName("com.mysql.jdbc.Driver");
database = DriverManager.getConnection("jdbc:mysql://***:" + 3307 + "/**db", "", "");
} catch (Exception e) {
e.printStackTrace();
}
}
My exception:
> java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
I am trying to connect Msaccess database with my java webapplication using the following code:
import java.sql.*;
public class connection {
public static void main(String[] args) {
try {
// Load MS accces driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("loaded");
String url = "jdbc:odbc:OnboardingTT";
System.out.println("assigned");
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url,"","");
System.out.println("Connection Succesfull");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}}}
But connection is not established. and the error is
loaded
assigned
Got an exception!
null
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(Unknown Source) at
sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
connect.connection.main(connection.java:18)
I also tried with
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb,*.accdb)};DBQ="+ "C:\\OnboardingTT.mdb";
Is this code correct or i have to do any changes in this please answer my question
Looks like something went wrong with the DB connection, maybe the DB is not online, maybe the user or the password are incorrect...
Please provide more info to help us to help you.
;-)
Can anyone help me? I've already tried to solve this for one hour and I'm still confused.
Below is my code and i get this error when compiling.
Output msg::
DriverLoaded
Could Not Connect to Databasejava.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnect.<init>(DBConnect.java:11)
at DBConnect.main(DBConnect.java:21)
Code::
import java.sql.*;
public class DBConnect {
public DBConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DriverLoaded");
String url = "jdbc:odbc:; DRIVER = Microsoft Access Driver (*.mdb, *.accdb); DBQ = DB.accdb";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection Established Successfully");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Could Not Connect to Database");
}
}
public static void main (String args[]) {
DBConnect dbcon = new DBConnect();
}
}
Overloaded methods for getConnection()
1)
getConnection( String url, Properties info )
url -
a database url of the form jdbc:subprotocol:subname
info -
a list of arbitrary string tag/value pairs as connection arguments;
normally at least a "user" and "password" property should be included
2)
getConnection( String url, String user, String password )
url - a database url of the form jdbc:subprotocol:subname
user -
the database user on whose behalf the Connection is being made
password -
the user's password
3) getConnection( String url )
url -
a database url of the form jdbc:subprotocol:subname
Considering you're using the last constructor, it seems your url syntax in incorrect. I'm not familiar with MS Access, but I'll offer a suggestion I found on another answer.
This is your syntax
"jdbc:odbc:; DRIVER = Microsoft Access Driver (*.mdb, *.accdb); DBQ = DB.accdb"
A correct syntax I found was
File f = new File("\\\\***\\***\\****\\***.accdb");
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getAbsolutePath();
Looks like you have an unnecessary semicolon after odbc and an extra space. Maybe you want to try the above syntax and see what happens. I'm not sure about the file part, but you may want to look into it if your url still fails after making the semicolon/space fix.
Check out this question also for more info on another option Connection with username and password
below is the working code for your problem...
import java.sql.*;
public class DBConnect {
public DBConnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DriverLoaded");
String url = "jdbc:odbc:instance";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection Established Successfully");
} catch(Exception e) {
e.printStackTrace();
System.out.println("Could Not Connect to Database");
}
}
public static void main (String args[]) {
DBConnect dbcon = new DBConnect();
}
}
steps to be followed:
create an access database DB.accdb in any directory of your windows xp system.
open start > controlpanel > Performance and maintanance > Administrative Tools > Data sources (ODBC) >click System DSN tab > click add > choose Microsoft Access Driver (accdb,mdb) > give the name : instance , (since, getConnection("jdbc:odbc:instance") and click and browse the DB.accdb located in your hard drive ) press ok and restart your command prompt. and run the code again.
Running the same code in eclipse
create a java project.
add a main class and edit the source of this main class. just copy and paste the about code.
create a user library by adding the jar files from the jdk/bin directory.
link the build path to the project by linking the userlibrary.
run the project.
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.
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.