JDBC Driver Does Not Exist - java

I’m trying to connect a Java program to a remote Oracle DB. After doing some research online, I decided that the easiest way to do this was with the Oracle JDBC driver. I downloaded and ran the jar file and got the message “***** JCE UNLIMITED STRENGTH IS INSTALLED *****.” The problem is that when I try to add the driver to my classpath (javac -classpath ojdbc8.jar Connect.java), I keep getting an error message saying “package oracle.jdbc.driver does not exist.” I’ve been researching how to fix this online, but I’m only getting confused. Any ideas on what I did wrong?
import java.sql.*;
public class Class1 {
public static void main (String args [])
throws SQLException
{
// Load the Oracle JDBC driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
// Connect to the database
// You must put a database name after the # sign in the connection URL.
// You can use either the fully specified SQL*net syntax or a short cut
// syntax as `<host>`:`<port>`:`<sid>`. The example uses the short cut syntax.
Connection conn =
DriverManager.getConnection ("jdbc:oracle:thin:hr/hr#myhostname:1521:orcl",
"myUsername", "myPassword");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select the ENAME column from the EMP table
ResultSet rset = stmt.executeQuery ("select ENAME from EMP");
// Iterate through the result and print the employee names
while (rset.next ())
System.out.println (rset.getString (1));
conn.close(); // ** IMPORTANT : Close connections when done **
}
}
The error is:
java: package oracle.jdbc.driver does not exist

Can you try to run the sample DataSourceSample.java? Make sure you have the JDBC driver in the classpath. You can also refer to this quickstart for detailed instructions.

Related

When I run SQL query from RIDE it gives error

I am having this problem,
When I send an SQL query as an argument it gives error
when I use the same query directly in my java program it works fine.
MY SQL query when I send as an argument is as follow
Select RATINGPERIOD from INVESTMENT.I1INVE Where INVESTMENTID = 100
rs = stmt.executeQuery(sqlQery); // Select RATINGPERIOD from INVESTMENT.I1INVE Where INVESTMENTID = 100
and when I use it directly into my java program is as follow
try
{
// Load the driver
Class.forName("com.ibm.db2.jcc.DB2Driver");
System.out.println("**** Loaded the JDBC driver");
// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
con = DriverManager.getConnection (url, user, password);
// Create the Statement
stmt = con.createStatement();
System.out.println("**** Created JDBC Statement object");
// Execute a query and generate a ResultSet instance
rs = stmt.executeQuery("Select RATINGPERIOD from INVESTMENT.I1INVE where INVESTMENTID = 100");
while (rs.next()) {
delay = rs.getString("RATINGPERIOD");
System.out.println("size of list ="+delay);
}
}
Error log
com.ibm.db2.jcc.am.SqlException: [jcc][10103][10941][3.62.57] Method executeQuery cannot be used for update. ERRORCODE=-4476, SQLSTATE=null
at com.ibm.db2.jcc.am.fd.a(fd.java:660)
at com.ibm.db2.jcc.am.fd.a(fd.java:60)
at com.ibm.db2.jcc.am.fd.a(fd.java:120)
at com.ibm.db2.jcc.am.jn.a(jn.java:4129)
at com.ibm.db2.jcc.am.jn.a(jn.java:2875)
at com.ibm.db2.jcc.am.jn.a(jn.java:679)
at com.ibm.db2.jcc.am.jn.executeQuery(jn.java:663)
at com.profitsoftware.testing.utils.keywords.date.DatabaseSQL.sqlQuery(DatabaseSQL.java:46)
at com.profitsoftware.testing.utils.keywords.date.DatabaseSQLKeywords.executeSqlQuery(DatabaseSQLKeywords.java:18)com.
ok some more information, I have assigned sql query to a string in Java program and then compared it to the query(String) I was getting as argument in my java program and it gives false. which explain maybe when query is passed from RIDE to Java programm it changes somehow. any idea what happens there ?
Thanks in advance and sorry if it sounds a stupid question, I a new to this programming world.
oK, It started to work, actually I was missing something there, so type. My logic itself was good but it was typo that created the problem
--Sara

How do I find Oracle 12c connection URL?

I am using eclipse and java to connect to an oracle 12c database. But every time I run through the process, I get a connection fail error that reads:
java.sql.SQLException: Invalid Oracle URL specified
Here is what my code looks like:
import java.sql.*;
public class JdbcConnection {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin#localhost:1521:xe", "username", "password");
Statement statement = con.createStatement();
String sql = "select * from employees";
ResultSet rs = statement.executeQuery(sql);
while (rs.next())
System.out.println(rs.getInt(3) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I am using a windows 7 sp1 Ultimate (64 bit)
CPU: i5 2.85 ghz
RAM: 8GB
Oracle is installed in a separate hard drive (in the same computer).
EDIT:I have tried the first suggestion from this post: How do you find out the Oracle database's URL?
and I get an error that says:
ORA-00928: SELECT KEYWORD MISSING...
This error occurs when I run the oracle "SQL DEVELOPER" application on the startup menu and type the suggestions from post above.
Note: I want to connect to the database from eclipse and query it programatically.
Is there a way to find out what the correct connection URL is?
Please help.

Teradata external Java Stored Procedure error: No suitable driver found for jdbc:default:connection

I wrote a Java stored procedure, packed it into a jar and installed it into the Teradata database. I want to use the default database connection as described here. Most of the code was generated by the Teradata wizard for stored procedures.
public class TestSql {
public static void getEntryById(int id, String[] resultStrings) throws SQLException {
Connection con = DriverManager.getConnection("jdbc:default:connection");
String sql = "SELECT x FROM TEST_TABLE WHERE ID = " + id + ";";
Statement stmt = (Statement) con.createStatement();
ResultSet rs1 = ((java.sql.Statement) stmt).executeQuery(sql);
rs1.next();
String resultString = rs1.getString(1);
stmt.close();
con.close();
resultStrings[0] = resultString;
}
}
I installed the jar:
CALL SQLJ.REPLACE_JAR('CJ!/my/path/Teradata-SqlTest.jar','test');
And created the procedure:
REPLACE PROCEDURE "db"."getEntryById" (
IN "id" INTEGER,
OUT "resultString" VARCHAR(1024))
LANGUAGE JAVA
MODIFIES SQL DATA
PARAMETER STYLE JAVA
EXTERNAL NAME 'test:my.package.TestSql.getEntryById(int,java.lang.String[])';
Now when I call this procedure, I get this error message:
Executed as Single statement. Failed [7827 : 39001] Java SQL Exception SQLSTATE 39001: Invalid SQL state (08001: No suitable driver found for jdbc:default:connection).
Now when I log off from Teradata and log on again and call the procedure, the error message becomes:
Executed as Single statement. Failed [7827 : 39001] A default connection for a Java Stored Procedure has not been established for this thread.).
What is the problem here? I'm connecting to Teradata using the Eclipse plugin. Teradata v. 15.0.1.01.
After many hours I finally found the problem. Eclipse packed all dependencies into the jar - which basically is ok. However it also packed the Teradata JDBC driver files (tdgssconfig.jar and terajdbc4.jar) into the result jar, which was the problem.
I adjusted the jar building process so that these files are not included and the errors went away.

No suitable driver found when making SQL connection to MS Access Database in java

I have a Jbutton (GetDataFromDB) in a simple java application that is suppose to load the data from the database depicted in the path in the code below into a Jtable in the application.
Edited answer into code:
private void GetDataFromDBActionPerformed(java.awt.event.ActionEvent evt) {
Connection con;
ResultSet rs = null;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={MS Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
stmt = con.createStatement();
String query = null;
query = "select * from cost";
rs = stmt.executeQuery(query);
i = 0;
while (rs.next()){
i = i + 1;
jTable.getModel().setValueAt(rs.getString(1), i, 1);
jTable.getModel().setValueAt(rs.getString(2), i, 2);
}
rs.close();
stmt.close();
con.close();
} catch(Exception err){
System.out.println(err.getMessage());
}
}
When I press the button I get the following message in the run output window:
No suitable driver found for jdbc:odbc:Driver={Microsoft Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I have at the top of my code the import:
import java.sql.*;
I have also tried changing from "Microsoft Access Driver" to "MS Access Driver" but I get the same message in the run output window i.e.
No suitable driver found for jdbc:odbc:Driver={MS Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I'm really thankful for all your help, input and feedback.
Depending on the driver and If you are pre JDK 6**!
You need to register the driver.
Try adding:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
So:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
It's also worth mentioning you don't need to do this every time you get a connection, just once to make sure the class is loaded.
There are a lot of stackoverflow questions relating to this, but the reason for it is below:
Source - From The Java Tutorial:
In previous versions of JDBC, to obtain a connection, you first had to
initialize your JDBC driver by calling the method Class.forName. This
methods required an object of type java.sql.Driver. Each JDBC driver
contains one or more classes that implements the interface
java.sql.Driver. ... Any JDBC 4.0 drivers that are found in your class
path are automatically loaded. (However, you must manually load any
drivers prior to JDBC 4.0 with the method Class.forName.)
On a related and very important note.
I would also recommend looking up how to handle connections. External Resources like database connections and cursors are easy to leak if you are not familiar with them. Look up 'try finally blocks', or more recently in java 7+ 'try-with-resources'.

SQL statement - NullPointerException

I have been assigned a task at work but i'm a beginner in Java and Eclipse.
I have to re-use an existing programm and modify some parts of it.
The following part does'nt work:
private java.sql.Connection conn;
private final String sqlRequest = "select ... from ...";
//................
private void DBConnect(){
try {
// Load the driver
java.lang.Class.forName(jdbcdriver).newInstance();
// Connect to database
conn = java.sql.DriverManager.getConnection(jdbcURL,dbuser,dbpwd);
//................
private void search2() {
try {
// create SQL statement
java.sql.Statement stmt = conn.createStatement(); //my line 135
java.sql.ResultSet rs = execRequest(stmt,sqlRequest);
//................
The error message in eclipse is :
"java.lang.NullPointerException at mon_prog.search2(mon_prog.java:135)"
This part used to work before... so is the problem due to my JDK version? I have JDK7u2
Get the connection first ...using..
Connection conn = DriverManager.getConnection(connection string);
Your conn seems null.
Have a look into great Vogella tutorial on how to connect to MySQL database from java program (IDE neutral way): http://www.vogella.de/articles/MySQLJava/article.html
Example steps to connect to your database:
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
Set breakpoints on the Class.forName() and getConnection() calls in DBConnect(), and on your line 135, then run it all through the debugger. I wouldn't be the least bit surprised if getConnection() doesn't get executed before you try to use the connection. (Been there, done that, got the source control commit.)
If that's not it, you may also want to double-check that you really don't have another variable that is shadowing your intended conn instance. "Go to definition" is very useful for this; just make sure you end up in the expected place.

Categories