I am following Java: How To Program - Chapter 24. The chapter deals with database implementation in Java. I followed the steps to setup "Derby", but I get the error java.sql.SQLException: Database 'books' not found..
I checked $PATH to make sure it includes $DERBY_HOME. $DERBY_HOME points to the correct folder(/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home/db).
I checked $JAVA_HOME and it was also setup correctly(/Library/Java/JavaVirtualMachines/jdk1.8.0_101.jdk/Contents/Home).
I can use the tool ij and it shows me the database that is setup. I added derby.jar to the package in eclipse. The following is the code from the book, but when I compile it I get the error java.sql.SQLException: Database 'books' not found.
I looked it up online, and there were recommendations that I add //localhost:1527/books. But if I add that I get the java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/books error.
There was also suggestions that I use Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();, that didn't solve the problem either.
I have copy/pasted the books.sql database in the same package as the one that contains the source code.
Does anybody know how to solve the problem? I am running MacOS Sierra.
public class DisplayAuthors {
public static void main(String [] args) {
final String DATABASE_URL = "jdbc:derby:books";
final String SELECT_QUERY = "Select authorID, firstName, lastName from authors";
try(
Connection connection = DriverManager.getConnection(
DATABASE_URL, "deitel", "deitel");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_QUERY)){
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfCols = metaData.getColumnCount();
System.out.printf("Authors of table of Books databse:%n%n");
for(int i = 0; i < numberOfCols; i++)
System.out.printf("%-8s\t",metaData.getColumnName(i));
System.out.println();
while(resultSet.next()){
for (int i = 1; i <= numberOfCols; i++)
System.out.printf("%-8s\t",resultSet.getObject(i));
System.out.println();
}
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
I figured the problem was. When the creating the database via ij I had to be in the same directory that the source file is. Now under eclipse I thought that this would mean I need to be under package folder(JAVAProject/src/package), but that was wrong. I had to be under (JAVAProject).
Related
I have been starting off with some JDBC a few days ago as of 2019/3. And there was this error occurring when I try to comply the code below in my eclipse IDE.
I actually did some research before this and I have tried:-
-Adding external libraries from the project menu
-Reinstalling and trying out different ides(thinking it was just eclipse but turns out its something about my system)
-reinstalled both jdk and the jdbc connector
and still, the problem persists.
import java.sql.*;
public class Driver{
public static void main(String[]args)throws Exception {
String url = "jdbc:mysql://localhost:3306/main";
String uName = "Ng Jun Han";
String pW = "password";
String query = "SELECT first FROM students WHERE id = 1";
Class.forName("com.sql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uName, pW);
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
rs.next();
String name = rs.getString("first");
System.out.print(name);
st.close();
con.close();
}
}
This is how my project directory looks like
My biggest concern regarding the topic is about something wrong I did with the installation methods. Mainly because there are not much up-to-date resources to follow.If so, does anyone know the CORRECT way of fixing it?(the driver jar file is located at C:\Program Files\MySQL , and i c/p-ed it into my the libraries file in my project directory) Thanks for helping:)
Try this class name :
Class.forName("com.mysql.cj.jdbc.Driver")
Refer to the official docs
i ran select command and printed the result in system.out using below code. was getting expected result with invalid cursor error.
could you please any one tell, why this error was occurred after printing the expected result and how to fix it?
code:
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "path";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
String select="SELECT DISTINCT col1,col2 FROM Tablename";
ResultSet rs = stmt.executeQuery(select);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
String columnValue;
while (rs.next())
{
for (int i = 1; i <= columnsNumber; i++) {
columnValue= rs.getString(i);
System.out.print(columnValue+" ");
}
}
}
catch(SQLException exc){
exc.printStackTrace();
}
output:
test1 result1
test2 result2
test3 result3
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6964)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7121)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3914)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353)
I was able to recreate your issue. It appears to be an "unfortunate behaviour" of the JDBC-ODBC Bridge and the Access ODBC driver when working with SELECT DISTINCT ... queries and ResultSet.TYPE_SCROLL_SENSITIVE.
The following kluge seems to work around the issue for me:
String select="SELECT * FROM (SELECT DISTINCT FirstName,LastName FROM Clients)";
Switching from ResultSet.TYPE_SCROLL_SENSITIVE to ResultSet.TYPE_FORWARD_ONLY also appears to avoid the issue.
However, since the JDBC-ODBC Bridge is obsolete and has been removed from Java 8 you might consider using the UCanAccess JDBC driver instead. For more details see
Manipulating an Access database from Java without ODBC
When trying to run a program that interfaces with Access 2010 it throws the error
WARNING:Looking for usage map at page 1774, but page type is 1
and then proceeds to throw errors about user lacks privilege to access the table I'm trying to use.
This program seems to work perfectly fine when using Access 2013, and it worked once on Access 2010 when I tried the update statement for the first time. Now it doesn't work at all.
I can't seem to find any reference to this error anywhere online, so I'm hoping someone else has encountered it before.
It throws an error on this line of code, which it doesn't do when interfacing with Access 2013:
ResultSet rSet = stmt.executeQuery("Select * FROM Players");
The entire method is:
public int addPlayer(String name, int x) throws SQLException //drafts a person to team x (ownerID)
, ClassNotFoundException
{
//Database db = new DatabaseBuilder().setCodecProvider(new CryptCodecProvider()).open(new File("BBFBLMasterVersion3.accdb"));
Connection con;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection("jdbc:ucanaccess://C:/Users/Andrew/Dropbox/Public/Schoolwork/IRC/BBFBLMasterVersion3.accdb"); //name of ODBC driver
Statement stmt = con.createStatement();
//stmt.executeQuery("SELECT * FROM DraftNightQuery");
//ResultSet rSet = stmt.getResultSet();
ResultSet rSet = stmt.executeQuery("Select * FROM Players");
String[] split = name.split(" ");
String salary = "1";
while(rSet.next())
{
String lastName = rSet.getString("Last");
//int x = Integer.parseInt(salary);
if(split[0].toLowerCase().equalsIgnoreCase(lastName))
{
String firstName = rSet.getString("First"); //get the item from column named Team Name
if(split[1].toLowerCase().equalsIgnoreCase(firstName))
{
Statement connec = con.createStatement();
Statement idMatch = con.createStatement();
String id = rSet.getString("ID");
connec.executeUpdate("UPDATE Players SET OwnerID = "+x+" WHERE Last ='"+split[0]+"' AND First='"+split[1]+"' ");
//stmt.executeUpdate(whoToAdd);
ResultSet temp =idMatch.executeQuery("SELECT * FROM Salaries WHERE ID ='"+id+"'");
while(temp.next()){
String tempID = rSet.getString("ID");
if(id.toLowerCase().equalsIgnoreCase(tempID)){
salary = temp.getString("Salary");
}
}
con.close();
connec.close();
stmt.close();
idMatch.close();
return Integer.parseInt(salary);
}
}
}
return 1;
}
finally{}
}
As Gord said, the problem is detected and logged by jackcess and it's likely caused by a accdb file corruption (I would try to fix it with the Compact and repair Access tool). Also, it may be in turn caused by its use in a sync dropbox folder. Thus, that the file was modified via UCanAccess or in another way is irrelevant, because all happened at a lower layer. Please, find similar issues reported in the jackcess forum (yes, they are googlable, did you remove the page number?)
The Problem:
I am creating an application that requires the use of an integrated database but I am having issues getting my application to connect to the database/table. Unfortunately, my knowledge of Java connecting to databases is rather limited but everything I have read and watched seems to point to my code being correct.
My Code:
public static void main(String[] args) {
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection con = DriverManager.getConnection("jdbc:derby:datahold;");
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from APP.DATASTORE");
ResultSetMetaData meta=rs.getMetaData();
int columnCount = meta.getColumnCount();
for (int x = 1; x <= columnCount; x++)
System.out.format("%20s",meta.getColumnName(x)+ " | ");
while (rs.next()){
System.out.println("");
for (int x = 1; x <= columnCount; x++) System.out.format("%20s", rs.getString(x)+ " | ");
}
if (stat != null) stat.close();
if (con != null) con.close();
} catch(Exception e) {
System.out.print(e);
}
}
The Error:
java.sql.SQLSyntaxErrorException: Table/View 'APP.DATASTORE' does not exist.BUILD
SUCCESSFUL (total time: 1 second)
My Data Base Setup:
I have tried removing the "APP." but this then results in the application not being able to find a table "ROOT.DATASTORE".
If anyone is able to help me out here that would be great!
UPDATE:
I can now see that when running the application, it is creating the database files in the root of the package. Therefore, the embedded driver connection must be working (at least that's the way I see it). My question is should the database be located here or should it be held in the "dist" folder?
I am assuming it is not able to see the table because it is looking in the wrong location.
You have put an semicolon there
DriverManager.getConnection("jdbc:derby:datahold;");
remove it
here is correct code
DriverManager.getConnection("jdbc:derby:datahold");
So the answer to this question is rather simple as I found out after HOURS of tinkering.
Netbeans kindly creates a persistent xml file that stores some data that the application uses when it starts up. More precisely, when the database starts up. One of these options is which connection to use.
All I had to do was change this connection to my embedded driver connection and it is now working.
Guys,
I know there are some new features in JDBC4.0 and one of them is that you don't need to load database drivers explicitly as the JDBC API will automatically load the driver when you call getConnection(). So I just wanna test it.
BTW, I use Eclipse as my Dev Tool.
Here are my code snippets:
public class Test002JDBCRowSet {
public static void main(String[] args) throws Exception{
String connURL = "jdbc:oracle:thin:#192.168.1.150:1521:";
String database = "bmdw";
String userName = "bmdw";
String passWd = "bmdw";
String driver = "oracle.jdbc.driver.OracleDriver";
String SQLStr = "select t.Empno, t.Ename, t.job, t.sal from employer t where t.sal > 1500";
/*
try{
Class.forName(driver);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
*/
//Latest Method4 : Search for some data with RowSet, offline!
RowSetFactory rsf = RowSetProvider.newFactory();
try(
Connection conn = DriverManager.getConnection(connURL + database,userName,passWd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStr);
CachedRowSet cachedRS = rsf.createCachedRowSet();){
cachedRS.populate(rs);
conn.close();
System.out.println("======Employee List -- Salary more than 1500======");
System.out.printf("%-15s%-15s%-15s%-15s%n","Employee No.","Employee Name","Employee Job","Employee Salary");
try{
while(rs.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
while(cachedRS.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
I got the runtime exception :
java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#192.168.1.150:1521:bmdw
However, if I remove the comments about loading oracle driver explicitly, it works well.
And I'm sure I have already add the ojdbc14.jar into classpath.
So I don't know what happened. I'm trying to figure out how does the method 'getConnection()' works.
I checked System.getProperties() but there is no property named 'jdbc.driver'. Even if I added it and set the value to 'oracle.jdbc.driver.OracleDriver'. It still doesn't work.
I checked ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()) and I found there is only one default file :
jar:file:/D:/Java/jdk1.7.0_03/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
I has so far achieved little.
There might be some oversight in the configuration of Eclipse.
Hope anyone can help me.
Thanks.
I agree with #kordirko and his comment. OP also seems to have confirmed that his problem is resolved because of his comment. Hopefully he gets notification of this and makes it an answer. :)
Check this link: http://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcvers.htm#JJDBC28109 --> You need to have the ojdbc6.jar in your classpath environment variable in order to have JDBC 4.0 standard support. – kordirko