I've implement an application, it works when I code in Windows. But the same code gave Exception in Mac. I use SQLite database and have put sqlite-jdbc-3.21.0.1.jar as library.
I know the driver went ok since I have check it like below:
public static void pureSqlite() throws Exception {
String url = "jdbc:sqlite:hadits-bukhari.sqlite";
Connection connection = DriverManager.getConnection(url);
System.out.println("Connection established.");
String sql = "SELECT * FROM hadits";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
int i = 0;
while (resultSet.next()) {
if (i == 5) break;
System.out.println(resultSet.getInt("nomer")+". "+resultSet.getString("deskripsi"));
i++;
}
}
It works perfectly when I used my Windows computer.
Then, I've implement it with ORMLite's way. Create Hadits class with required annotation. Then I have below function:
public static void withOrmLite() throws Exception {
Class.forName("org.sqlite.JDBC"); // even put this test
System.out.println("Frankly, class org.sqlite.JDBC is exists.");
Ilmu ilmu = new IlmuImpl();
List<Hadits> list = ilmu.findHadits("bukhari", "");
int i = 0;
for (Hadits item: list) {
if (i == 10) break;
System.out.println(item.number+". "+item.desc);
i++;
}
}
From IlmuImpl:
#Override
public List<Hadits> findHadits(String book, String keyword) throws Exception {
String dbHost = "jdbc:sqlite:hadits-"+book+".sqlite";
ConnectionSource connection = new JdbcConnectionSource(dbHost);
Dao<Hadits, Long> haditsDao = DaoManager.createDao(connection, Hadits.class);
List<Hadits> list;
if (keyword == null || keyword.trim().length() == 0) {
list = haditsDao.queryForEq("buku", book);
} else {
QueryBuilder<Hadits, Long> queryBuilder = haditsDao.queryBuilder();
queryBuilder.where().like("deskripsi", "%"+keyword+"%");
PreparedQuery<Hadits> preparedQuery = queryBuilder.prepare();
list = haditsDao.query(preparedQuery);
}
connection.close();
return list;
}
This code do fine in Windows, but failed when I use the same code in Mac, says:
Exception in thread "main" java.sql.SQLException: Driver class was not found for SQLite database. Missing jar with class org.sqlite.JDBC.
at com.j256.ormlite.misc.SqlExceptionUtil.create(SqlExceptionUtil.java:27)
at com.j256.ormlite.db.BaseDatabaseType.loadDriver(BaseDatabaseType.java:47)
at com.j256.ormlite.jdbc.JdbcConnectionSource.initialize(JdbcConnectionSource.java:137)
at com.j256.ormlite.jdbc.JdbcConnectionSource.<init>(JdbcConnectionSource.java:117)
at com.j256.ormlite.jdbc.JdbcConnectionSource.<init>(JdbcConnectionSource.java:59)
at ilmu.implementation.IlmuImpl.findHadits(IlmuImpl.java:17) <-- this is my class
...
Caused by: java.lang.ClassNotFoundException: org.sqlite.JDBC
...
What could be wrong?
Caused by: java.lang.ClassNotFoundException: org.sqlite.JDBC
The exception is trying to tell you all that you need to know. Although you say that you "put sqlite-jdbc-3.21.0.1.jar as library", the JDBC class is not found. This means that there is something wrong with your classpath.
Either the library hasn't been added to the right directory or hasn't been properly identified as a dependency in your IDE, maven, or other build utility. If you give more details about your build environment, I can provide more specifics about tuning the dependencies.
Related
The error is that I cant open the connection to mysql database, it must be an error in parameters but I am confused , I have no idea where is the problem.
First you need to create a MySQL schema. Secondly, use JDBC to connect to your recently created database (via localhost - make sure you get the user/password right).
After that you should use DAO-like classes. I'll leave here a Connect class:
public class Connect {
private static final String USERNAME = "root";
private static final String PASSWORD = "12345";
private static final String URL = "localhost";
private static final String SCHEMA = "new_schema";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connect() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+URL+"/"+SCHEMA+"?user="+USERNAME+"&password="+PASSWORD);
}
}
After you have the Connect class, you should connect to the database using Connection c = Connect.connect(). Here's a class that implements it.
public static List<Album> list() throws SQLException {
Connection c = Connect.connect();
ResultSet rs = c.createStatement().executeQuery("SELECT * FROM Albums");
List<Album> list = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("nome"); // first table column (can also use 1)
String artist = rs.getString("artista"); // second table column (can also use 2)
Album a = new Album(name, artist);
list.add(a);
}
return list;
}
It should also give you an insight as to how you should use SQL commands.
If you'd like a more in-depth help you should post the code you used, otherwise it's difficult to give you a more "to-the-point" explanation.
JDBC URLs can be confusing. Suggest you try using a SQL tool that understands the JDBC protocol (such as the database development perspective in Eclipse) to validate the URL and make sure you can connect to the database before you start coding. Cutting and pasting a URL known to work into your code can avoid many problems.
I'm learning jdbc and working with Oracle database by writing this simple code. The IDE i'm using is MyEclips. But the problem is when I compile and run this program in command prompt it works properly but when I try to compile and run this program in my IDE i.e. MyEclips it through an error message:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
import java.sql.*;
class OracleCon{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = null;
String URL = "jdbc:oracle:thin:#localhost:1521:xe";
String UN = "HR";
String PASS = "12345";
con = DriverManager.getConnection(URL,UN,PASS);
Statement stmt = con.createStatement();
String sql = "SELECT * FROM EMPLOYEES";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
I also set the class path in Environment variable.Environment variable snippet
Verify that the name of the requested class is correct and that the appropriate .jar file exists in your classpath. If not, you must explicitly add it to your application’s classpath.
In case the specified .jar file exists in your classpath then, your application’s classpath is getting overriden and you must find the exact classpath used by your application.
In case the exception is caused by a third party class, you must identify the class that throws the exception and then, add the missing .jar files in your classpath.
While the build paths are not correct I obtain “com.microsoft.sqlserver.jdbc.SQLServerDriver” from the stack trace. As they are built correctly, I obtain my printed statement “Successfully connected”. The JDBC is living within the getter/setters of the webservice as a method.
When I place the JDBC content in its own file with no builds and run as a java application I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
When I place the JDBC content in its own file with builds and run as a java application I receive: “Successfully connected”
When the method is called from a test file as a java application I receive: “Successfully connected”
Ex:
public static void main(String[] args) {
insert.main(args);
When the method is run as a java application on PO I receive: “Successfully connected”
When I place the method to be called under a setter (which will be invoked by the client, which will cause the jdbc to be invoked) I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Would you happen to have any tips for me? I’m clueless why it will work under being invoked as an application but not via client?
public class insert{
public static void main(String[] args) {
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
Any tips at this point would be greatly appreciated.
The problem is that your jar misses the necessary libraries that provides com.microsoft.sqlserver.jdbc.SQLServerDriver class and others to communicate with your SQL server. You have to make sure the library is loaded and available when is being executed from tomcat. Just copy your library and drop it inside %TOMCAT_INSTALL%/lib folder, where %TOMCAT_INSTALL% is the folder where your tomcat is installed, so the library will be available for every project (war, jar, etc) that runs in your tomcat installation.
I am trying to get data from mysql database by rmi,
When the client request the service from the server and trying to connect to db to get data
NO Suitable driver Exception rise !
or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
(Implementation Class)imp.java:
public class imp extends java.rmi.server.UnicastRemoteObject implements inter {
...
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
public String getName() throws java.rmi.RemoteException {
String name = "none";
try {
PreparedStatement ps = con.prepareStatement("select ....");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString("f_name");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return name;
}
}
(Interface)inter.java:
public interface inter extends java.rmi.Remote {
public String getName() throws java.rmi.RemoteException, SQLException;
}
(Server)Server.java:
public Server() throws RemoteException, MalformedURLException {
server_object = new imp();
Naming.rebind("rmi://localhost:1099/myserv", server_object);
}
(Client) client.java:
myobject = (inter) Naming.lookup("rmi://localhost:1099/myserv");
myobject.getName();
I Put the mysqlconnector library in the folder of classes
Any Help?
The exception :java.lang.ClassNotFoundException: com.mysql.jdbc.Driver,causes whenever we forget to add jar file for mysql connector. pls add mysql connector jar file to your projects classpath, and run it.
Edited:
you can download it from here : http://code.google.com/p/find-ur-pal/downloads/detail?name=mysql-connector-java-5.1.18-bin.jar& or from here : http://dev.mysql.com/downloads/connector/j/5.0.html
Extract mysql_connector jar file into three folders in the classes folder.
Like this : com folder, META-INF folder, and org folder.
I know this has been asked before but I really can't get this to work and as far as I can see I've followed all the steps.
I'm using Eclipse.
So I downloaded the Microsoft SQL Driver sqljdbc v4.0.
I created a new project and class. I edited the build path by adding the .jar file to the libraries.
I typed the following code:
package com.test.sql;
import java.sql.*;
public class Connect
{
public static void main (String[]args)
{
Connection con = null;
String conURL = "jdbc:sqlserver://localhost; databaseName=AnotherTestDB;";
try
{
con = DriverManager.getConnection(conURL);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I got the following error:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost; databaseName=AnotherTestDB;
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.test.sql.Connect.main(Connect.java:11)
A bit more research and I was told put it in the java /lib/ext and reference it from there.
Nothing changed.
Any help?
Thanks.
Normally you need to register the driver before accessing to it:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Try with something like this:
String DRIVER = “oracle.jdbc.driver.OracleDriver”;
String DBURL = “jdbc:oracle:thin:#jiplc0.si.ehu.es:1512:Erreala”;
String UID = “USERNAME”;
String PWD = “PASSWORD”;
Driver kontrolatzailea = (Driver) (Class.forName(DRIVER).newInstance());
DriverManager.registerDriver(kontrolatzailea);
DefaultContext test = new DefaultContext(DBURL, UID, PWD, false);
DefaultContext.setDefaultContext(test);
Thanks for the responses.
I had both the sqljdbc4.jar and sqljdbc.jar referenced. The version of Java I am using requires that I use sqljdbc4.jar but it was being overwritten by sqljdbc.jar so I removed it.
I also changed my code to this:
public static void main (String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://nameMyLaptop//SQLEXPRESS";
Connection con = DriverManager.getConnection(connectionUrl);
}
//Insert catches
}
Apparently I didn't have to change the code but its not giving me that error now. I'm getting a new one but that's unrelated to my question.
Thanks for your time and responses.
You have to add the SQL JDBC Driver in your project libraries. download jtds.jar and add to your libraries. And follow the code below.
public static void main (String[] args) throws Exception{
Connection conn=null;
String url="jdbc:jtds:sqlserver://YourServerIp:1433/dbName";
String username="sa";
String password="****";
String driver="net.sourceforge.jtds.jdbc.Driver";
// Step 1: Load the JDBC driver.
Class.forName(driver);
// Step 2: Establish the connection to the database.
conn= DriverManager.getConnection(url, username,
password);
}
Here you have to follow two steps......