Unable to figure out JDBC ClassNotFoundException (JTDS driver) - java

So a little background on my problem: I am trying to copy over a table on an Microsoft SQL system from an Oracle database. Besides giving password and user access to the table I cannot edit or do anything to the MSSQL database.
I successfully used the Oracle SQL Developer to connect and view the tables I want (using a third party JDBC driver), but I want to set up an automated copy-over into my Oracle database so I am attempting to use the same driver in some stored java code.
I have a java function that all it should do is go and count the number of entries in the table. So far my code looks like:
public static String getCount() {
Statement stmt = null;
Connection conn = null;
int rowCount = 0;
String message = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println("Error loading driver: " + e);
message = message + e + " -ER1 \n";
}
try {
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://site.school.edu:2000/ACCESS", "user", "password");
stmt = conn.createStatement();
String strSelect = "select 1 as field;";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next()) {
++rowCount;
}
}
catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + " -ER2";
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + "-ER3";
}
}
return message;
}
Which is being calling from a stored function :
CREATE OR REPLACE function Schema.java_testMessage return varchar2
as language java
name 'ConnectAndQuery.getCount() return java.lang.String';
Which I am calling from a script in TOAD:
set serveroutput on;
declare
words varchar2(400);
begin
words := KSL_ADMIN.java_testMessage;
dbms_output.put_line(words);
end;
However the result is that I'm getting:
java.lang.ClassNotFoundException: net/sourceforge/jtds/jdbc/Driver -ER1
08001 -ER2
PL/SQL procedure successfully completed.
I have the jar file within the class path, I can't think of any reason it shouldn't have the nessecary permissions to see the jar, and as far as I can tell I have everything spelled correctly.
Please help me figure out what I am doing wrong. Or if there is perhaps an easier way to go about connecting an Oracle DB to an MSSQL DB without really installing anything. Any knowledge on this is welcome as I am pretty new to a lot of this.

Oracle has its own internal java virtual machine and it does not use the system classpath. If you need external libraries you must “load” them into the internal JVM. You can do this using Oracle's loadjava tool.
See the Oracle's loadjava documentation (http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheleven.htm#JJDEV10060)

Related

Willena sqlite jdbc cannot open SqlCipher db

I am trying to figure out how to encrypt a sqlite database in non-android java.
It does not seem to be super straight forward, but I Willena jdbc crypt which does seem to be able to create an encrypted database, but I simply cannot figure out how to access a SQLCipher 4 encrypted database with it.
Here is my code.
String path = "jdbc:sqlite:C:\\Users\\User1\\Desktop\\testServer232.db";
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection(path+"?cipher=sqlcipher&key=a");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(3, 'leo1')");
statement.executeUpdate("insert into person values(4, 'yui1')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e.getMessage());
}
}
This code does work, but I don't think that it produces a SqlCipher 4 encrypted database. When I try to open it with DB browser for Sqlite, it does not allow me access when I put the password = a.
Where am I going wrong?
Ok, so I ended up finding the creator of the repository. And he solved it easily and answered really fast.
Here is the solution:
Here are a few things that could be tested:
Use version 3.31.1
Try to do the database connection using "jdbc:sqlite:file:C:\Users\User1\Desktop\test.db?cipher=sqlcipher&key=password123"as URI (notice the added "file:").
Try to add the legacy parameter for SQLCipher as available here (https://github.com/Willena/sqlite-jdbc-crypt#aes-256-bit-cbc---sha1sha256sha512-hmac-sqlcipher). The URI will become something like this: "cipher=sqlcipher&key=password123&legacy=4"
This is now working for me. I recommend that others use it if they are interested in an easy way to do sqlcipher version 4 similarly to how it is done in an android project.

MySQL 1064 syntax error when using statement

I am running a server that receives queries and sends them to the Database using Statements.
try{
connection = dbConnection.getDbConnection();
if(connection != null) {
System.out.println("DA2");
Statement mySt = connection.createStatement();
if(mySt != null) {
ResultSet myRs = mySt.executeQuery(query);
System.out.println("DA3");
while(myRs.next()){
//getting data and printing it
}
}
}
It prints DA2 so the connection is created succefully.
The query is send by the client in the following way
DataOutputStream out = new DataOutputStream(client.getOutputStream());
String query = "USE db_name; SELECT * FROM `tb_name`;";
out.writeUTF(query);
I changed the database name with db_name and the table name with tb_name(I am sure I wrote them correctly in my code).
The server receives them this way
Socket client = socket.accept();
DataInputStream input = new DataInputStream(client.getInputStream());
String query = input.readUTF();
When the server is running and the client sends the query an exception is thrown with the following message(I handled the exceptions to show me this).
SQLState: 42000
Error Code: 1064
Message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM `tb_name`' at line 1
The same query runs correctly on a MySQL database.
How can I solve this? Is the database sending back the error and so throwing an exception or is it just the code?
SOLVED: I forgot to specify the database name in the connection.
You could use (single SQL statement with qualified name):
String query = "SELECT * FROM db_name.`tb_name`";
public static Connection dbConnect() {
Connection c = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/DBNAME", "USERNAME", "PASSWORD");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException " + e);
} catch (SQLException e) {
System.out.println("SQLException " + e);
}
return c;
}
Hope you have created dbConnect in similar fashion.
Here We heve included the database name in get connection method
So explicitly no need to use database name for each time until you are accessing another database.
so your query should be
String query = "SELECT * FROM `tb_name`";

Java With Microsoft Access Database

I'm trying to use Ucanaccess library with java to connect to Microsoft Access ...
So i tried executing this code and it worked ....
String url = "jdbc:ucanaccess:\\C:/Access.ACCDB";
String query = "select * from [Donations]";
try
{
java.sql.Connection con =DriverManager.getConnection(url, "","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println("Account No: " + rs.getString(1));
System.out.println("Surname: " + rs.getString(2));
System.out.println("First Name: " + rs.getString(3));
}
}
catch(SQLException ex)
{
while (ex!=null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
let me explain what i'm trying to do
I have a Asp.Net website that uses Microsoft Access Database and in the same time i need a server (Java Application) to access the same Database (Microsoft Access) but when i uploaded the Database online to test if the server can get to the Database and modified the String for the connection ....
here is what it looked like
String url = "jdbc:ucanaccess://www.filetolink.com/download/?h=eaa4aab688d25e270539868d712961ab&t=1467140283&f=3ca9ad1869;";
String query = "select * from [Donations]";
try
{
java.sql.Connection con =DriverManager.getConnection(url, "","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println("Account No: " + rs.getString(1));
System.out.println("Surname: " + rs.getString(2));
System.out.println("First Name: " + rs.getString(3));
}
}
catch(SQLException ex)
{
while (ex!=null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
I tried running the code but I had an error message ... Here it is :
SQL Exception: UCAExc:::3.0.6 given file does not exist:
http:\www.filetolink.com\download\?h=e6dc57e3485defa7c53e1c968a87fb1f&t=1467139906&f=3ca9ad1869
So What i'm asking for is :
1.How can I publish the website with the access database and let both of the Server and the website access the Database ?? (The server and the website aren't on the same Machine or computer .... )
2.if the answer to my question is that i can't ... then what can i do ?? other suggestions ? for having Database that can be accessed by a Remote Server (Java Application ) and A website (Asp.Net)
MS Access is a desktop database not a server database management system. If a program wants to access to such a database, the database file has to be on a local or network filesystem. So if your two applications are running on different machines in the same intranet, putting the database file on network filesystem would be a solution.
BUT: MS Access was never meant to be used as a web application's backend database. You should use a real server database like MS SQL Server, PostgreSQL or MySQL instead. Then your applications can access the database via network protocol. Theoretically it is possible to open the database port to the internet so that you can connect from everywhere. But this is not recommended due to security reasons.
So if your two applications aren't running in the same intranet it is better to create some webservices and let your other program call these webservices to get the needed information.

SQLite Database locking up on Delete Command

I have a problem where I can't seem to get this simple delete command working. Everytime I run it it just locks the database and crashes
The id parameter exists in the database
the database is small. Only a few tables.
update commands work completely fine.
The id is an in and resulting command is - DELETE from Employees where ID = 2;
public static void EmployeeDeleteByID(int idIn){
Connection c = null;
Statement stmt = null;
try {
c = Connect();
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "DELETE from Employees where ID = " + idIn + ";";
System.out.println(sql);
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println("Error 1 : " + e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
Error after running : java.sql.SQLException: database is locked
"database is locked" means that some other connection still has an active transaction.
If there is no other process accessing the database, you have to check all connections in your program; at least one of them forgot a commit().
The code actually works fine.
It turned out another method was being called to fill a JCombo which was keeping a connection open due to an error being caused by calling a null value from database.
It wasnt obvious as there was no code in the exception box.
Silly little problem so people always make an error throw some kind of stack trace or warning.
Thanks

Why am I receiving this SQLException error stating that no suitable driver can be found?

I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);

Categories

Resources