I'm using the H2 database in my Java project (embedded mode).
On my computer at home everything works, the connection can be established, but on all other computers I always receive the following error:
org.h2.jdbc.JdbcSQLException: Table "CUSTOMERS" not found; SQL
statement: SELECT * FROM CUSTOMERS [42102-162]
I'm sure, that within the DB everything is alright, it should be something with the connection.
But even if I import the h2-1.3.162.jar file, the error still remains.
String dbClass = "org.h2.Driver";
String dbDriver = "jdbc:h2:~/cc";
String user = "user1";
String pass = "test1";
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void connect() {
boolean done = false;
//load driver
try {
Class.forName(dbClass).newInstance();
System.out.println("driver loaded"); // This is shown in the Compiler
} catch (Exception ex) {
System.out.println("error while loading driver");
System.err.println(ex);
}
// Connection
try {
conn = DriverManager.getConnection(dbDriver, user, pass);
System.out.println("connected"); // This is shown in the Compiler
done = true;
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
public Vector select() {
data = new Vector();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM CUSTOMERS");
while (rs.next()) {
Vector row = new Vector();
row.add(rs.getInt("id"));
row.add(rs.getString("fname"));
row.add(rs.getString("lname"));
row.add(rs.getString("street"));
row.add(rs.getString("city"));
row.add(rs.getString("zip"));
row.add(rs.getString("state"));
row.add(rs.getString("phone"));
row.add(rs.getString("birthday"));
row.add(rs.getString("email"));
row.add(rs.getInt("code"));
data.add(row);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
System.out.println("error while selecting"); // I receive this error
System.err.println(ex);
}
return data;
}
The problem isn't with your connection as you'd receive an exception well before then if it was failing to connect to the database. The exception is pretty clear about what the issue is, as well - it can't find the CUSTOMERS table. That could be because the table doesn't exist at all, or the connection is pointing at the wrong database; try putting in the full schema information of the table, rather than just its name, and see if that works.
I'm sure, that within the DB everything is alright, it should be
something with the connection. But even if I import the h2-1.3.162.jar
file, the error still remains.
Check your assumptions. This one is incorrect.
There's nothing in the message to suggest that you couldn't connect. Either you connected to the wrong database OR the one you did connect to didn't CREATE TABLE CUSTOMERS. (Should be named CUSTOMER, not plural.)
You'll fix your error faster if you stop assuming that everything you did is correct. You should be assuming that everything is wrong.
I'd print the stack trace when you catch that exception. It'll give you more information.
Finally I figured it out!
It had nothing to do with my tables, the database couldn't be found. When trying to connect to a database which can't be found with String dbDriver = "jdbc:h2:~/cc";, a new database with the name cc (in my case) will be created (of course an empty one with no tables) and the connection is established. That's why I haven't received any connection errors.
In the next step I tried to retrieve some data from the new created empty database and therefore received the error, that my table doesn't exist.
So I changed this line: String dbDriver = "jdbc:h2:file:lib/cc"; and copied into the lib directory of my application my old database cc.h2.db.
That's all!
PS: Here is a similiar problem: h2 (embedded mode ) database files problem
Related
I am trying to add records to a table in an HSQL database through Java.
I have an HSQL database I made through OpenOffice, renamed the .odb file to .zip and extracted the SCRIPT and PROPERTIES files (It has no data in it at the moment) to a folder "\database" in my java project folder.
The table looks like this in the SCRIPT file
CREATE CACHED TABLE PUBLIC."Season"("SeasonID" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,"Year" VARCHAR(50))
All fine so far, the database connects just fine in Java with this code:
public void connect(){
try{
String dbName = "database\\db";
con = DriverManager.getConnection("jdbc:hsqldb:file:" + dbName, // filenames prefix
"sa", // user
""); // pass
}catch (Exception e){
e.printStackTrace();
}
}
I have the following code to insert a record into "Season".
public void addSeason(String year){
int result = 0;
try {
stmt = con.createStatement();
result = stmt.executeUpdate("INSERT INTO \"Season\"(\"Year\") VALUES ('" + year + "')");
con.commit();
stmt.close();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(result + " rows affected");
}
I have a final function called printTables():
private void printTables(){
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM \"Season\"");
System.out.println("SeasonID\tYear");
while(rs.next()){
System.out.println(rs.getInt("SeasonID") + "\t\t" + rs.getString("Year"));
}
}catch (Exception e) {
e.printStackTrace(System.out);
}
}
Now if I run this sequence of functions:
connect();
printTables();
addSeason("2010");
printTables();
I get this output:
SeasonID Year
1 rows affected
SeasonID Year
0 2010
Now when I close the program and start it again I get exactly the same output. So the change made during the first run hasn't been saved to the database. Is there something I'm missing?
It's caused by write delay params in hsqldb, by default has 500ms delay synch from memory to files.
So problem is solved when it's set to false
statement.execute("SET FILES WRITE DELAY FALSE");
or set as you like based on your app behaviour.
So my workaround is to close the connection after every update, then open a new connection any time I want to do something else.
This is pretty unsatisfactory and i'm sure it will cause problems later on if I want to perform queries mid-update. Also it's a time waster.
If I could find a way to ensure that con.close() was called whenever the program was killed that would be fine...
I'm programming in java SE and I get an error when trying to access to create a connection to mysql. I can connect to mysql, in fact, the error shows up when running a bucle.
What I do in this program is to check for a String in the table Colors of my database and if it finds nothing it creates this String in the table with an autoincrementing id.
It works fine, but after having checked it for a while it gives me the error.
I attach the image of the error and the code where I create the connection.
public Integer codiColor(String col){
Integer codi=null;
if(col.equals(""))
return 1;
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, usuari, password);//here is the error
try {
Statement st = con.createStatement();
String sql = "SELECT CODICOL FROM COLORES where COLOR ='"+col+"'";
ResultSet res = st.executeQuery(sql);
if(res.next()){
codi = res.getInt("CODICOL");
}
try { res.close(); } catch (Exception e) {}
try { st.close(); } catch (Exception e) {}
}
catch(SQLException s){
JOptionPane.showMessageDialog(null, "Error:\n"+s.getMessage(),
"ERROR.",JOptionPane.ERROR_MESSAGE);
}
finally{
try { con.close(); } catch (Exception e) {}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return codi;
}
This code is the one that checks if the color already exists or not.
EDIT:
url = "jdbc:mysql://192.168.1.200:3306/mybbdd?zeroDateTimeBehavior=convertToNull";
The problem is that con is evidently a member variable where it should be a local variable. If this piece of code and others like it are called from multiple threads, a con value will be overwritten and therefore lost, so a connection leak will result. You will almost certainly also have other problems due to concurrent use of the connection. Make it a local variable.
NB you haven't needed the Class.forName() line since 2007. The close of the connection, statement, and result set would be redundant if you used try-with-resources. And you should use a prepared statement.
String sql = "SELECT CODICOL FROM COLORES where COLOR =?";
try (con = DriverManager.getConnection(url, usuari, password);
PreparedStatement st = con.prepareStatement(sql);
) {
st.setObject(1, col);
ResultSet res = st.executeQuery();
if(res.next()){
codi = res.getInt("CODICOL");
}
}
catch(SQLException s){
JOptionPane.showMessageDialog(null, "Error:\n"+s.getMessage(),
"ERROR.",JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
I find the way out. I googled the number the java error gave to me and I found that adding a registry key to be able to do more connections should work.
I first did it on the server, to allow more connections from clients but it didn't still work so I tried to do it on my computer and for now it works.
This is the link from microsoft
In your code you giving a new connection on every call but you need to understand your OS allows you Only Limited Connection.
after cross Limit it will Not allow you to make another Connection.
i don't know what's your requirement but if you really need Connection
So better option is that you need to make Connection Pool. If user required a connection to do some task then user can Take Connection from connection Pool and after Work Finished user can return that connection to connection pool.
For Achieve this you need to Design Your Configuration File Or you need Design interface library interface and implement according to your Requirement.
I am trying to figure out why my code is getting sent to the exception catch block and how to make this part of my log-in work correctly. The problem seems to be in Class.forName(driver); While debugging I noticed that I get an error, "variable source not available, source compiled with-out g-option". Is this the reason my code will not move onto the next step? if it is what do I need to fix it, and what does it mean?
I do have imported in my program.....
import java.sql.*;
import javax.swing.JOptionPane;
import java.sql.DriverManager;
private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:db1.mdb";
con = DriverManager.getConnection(db);
st = con.createStatement();
System.out.println("it actually ready this set of code!");
String un = UserName.getText().trim();
String pw = Password.getText().trim();
String sql = "select user,pass from Table2 where user='"+un+"'and pass='"+pw+"'";
rs=st.executeQuery(sql);
int count = 0;
while(rs.next()){
count = count+1;
}
if (count==1){
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
}
else if (count>1){
JOptionPane.showMessageDialog(null,"Duplicate User, Access Denied!");
}
else {
JOptionPane.showMessageDialog(null, "user doesn't exsist. ");
}
} catch (Exception ex){
System.out.println("exception 2 ");
}
// TODO add your handling code here:
}
Try removing .mdb from String db = "jdbc:odbc:db1.mdb";
and simply write String db = "jdbc:odbc:db1";
This might work for you!
Note this is gonna work on or below Java runtime 7 only
Since Java 8, the JDBC-ODBC Driver support has been removed. You can still do something like this to connect to MSAccess DB if you want.
Alternatively, you can use one of the many databases for which free JDBC drivers are available, like MySQL, PostgreSQL, SQLServer etc.
Get database connection object as below:
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=db1.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Also add code to print exception stack trace:
catch (Exception ex) {
System.out.println("exception 2 ");
ex.printStackTrace();
}
This is my code, this code should be execute just one time, But when my database already exist, The database created message has been displayed!
I want to see message just when database really created, not every time.
public static boolean createDatabase() throws Exception {
String query = "CREATE DATABASE IF NOT EXISTS LIBRARY3";
Statement st = null;
Connection con = DriverManager.getConnection(dbUrl, "root", "2000");
st = con.createStatement();
if (st.executeUpdate(query) == 1) { // Then database created
JOptionPane.showMessageDialog(null, "Database created");
return true;
}
return false;
}
This code always returns true, Why?
If its MySQL you need to check if database exists to take decision weather the database was really created
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'LIBRARY3'
It returns true because you are asking mysql to create the database only if it exists, so, if it exists there is no error, it just does not create it. What you can do is try to create it and, if it fails, check that the reason is that the database alreyady existed.
try {
statement = connection.createStatement();
String sql = "CREATE DATABASE DBNAME";
//To delete database: sql = "DROP DATABASE DBNAME";
statement.executeUpdate(sql);
System.out.println("Database created!");
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
} catch (ClassNotFoundException e) {
// No driver class found!
}
The query is successful each time. Do a separate query to check if the table exists and return message based on that result.
Read more about how to check whether a table exists here
Shorter way to do it:
SHOW DATABASES LIKE 'LIBRARY3';
If LIBRARY3 dont exist, you will get an empty string.
I have a big question...
I have a database java program creation.
I want to know if the database exists or not, and the if exists just connect, if not to create it.
I tried this one:
if (dbName.exists() == false) {}
THIS IS ALL THE CODE...
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");
THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW....
PARTIAL CODE THAT WORKS !
conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);
System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);
BUT I WANT SOMETHING LIKE:
FILE dbName = new FILE (url);
Statement stmt = new Statement;
if (dbName.exists() == true)
System.out.println("Database exists ! Connecting ... ");
else {
String sql = "CREATE DATABASE "+url;
stmt.executeUpdate (sql);
}
I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.
So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ...
AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.
It is not working.... not entering in the else more, and says that Exeption Database already exists.
Thanks you very much.
If it is a MySQL database, the following code should work. Other databases may give a different error code, but the general way should be clear. Important is that you connect to the instance, not a specific database initially. For creating the tables, you will need to connect to the newly created database. You can't use the instance connection that I use in my example for creating the tables:
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/",
"root", "admin");
statement = connection.createStatement();
String sql = "CREATE DATABASE DBNAME";
//To delete database: sql = "DROP DATABASE DBNAME";
statement.executeUpdate(sql);
System.out.println("Database created!");
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
} catch (ClassNotFoundException e) {
// No driver class found!
}
// close statement & connection
Without knowing much about what's going on here simply trying to connect to a database that doesn't exists should throw a TimeoutException error or something similar. Just catch the exception and do stuff if you cannot connect.
boolean canConnect = false;
Connection conn = null;
try{
conn = DriverManager.getConnection(...);
canConnect = true;
}(Exception ex){
canConnect = false;
}
if (!canConnect){
makeDatabase(...);
}
Enjoy your day!
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
Statement statement = connection.createStatement();
String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
statement.executeUpdate(sql);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly Note a Two things
The new driver class is `com.mysql.cj.jdbc.Driver'
The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits