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.
Related
I got a method that deletes a record in the database when inserting a tag value. when a record is deleted, a message in the console screen pops up saying "this record has been deleted ". It works fine when inserting a valid tag value. However, when I insert an invalid tag value that doesn't exist in my database it acts like it has deleted it and displays that previous message. Although within my method says if the outcome is not equal 1 (which is not true) return false, but it's apparently not validating the inserted data. Can anyone tell me what's the problem
public boolean DeleteWallet(String Tag) throws SQLException {
System.out.println("Deleting wallet");
Connection dbConnection = null;
Statement statement = null;
int result = 0;
String query = "DELETE FROM wallets WHERE Tag = '" + Tag + "';";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
System.out.println("The record has been deleted successfully");
// execute SQL query
result = statement.executeUpdate(query);
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
if (result == 1) {
return true;
} else {
return false;
}
}
The statement
System.out.println("The record has been deleted successfully");
is being printed before you actually perform any database operations statement.executeUpdate(query);
Instead, you should perform your database operation within your try statement, then print your success output. If the statement fails (IE an exception is thrown) the success statement will be skipped.
Additionally, instead of relying on the output the the executeUpdate(query) to determine if your query was successful, I would always assume your query or some operation before the query fails, and only return true if all database processing was successful.
Finally, the use of prepared statements will help make your query easier to read, use, and is better secured against SQLInjection attacks.
Example:
public class DatabaseOperations {
public boolean DeleteWallet(String Tag) {
//Query used for prepared statement
static final String DELETE_QUERY = "DELETE FROM wallets WHERE Tag=?";
System.out.println("Attempting to delete wallet using query:" + DELETE_QUERY);
//assume DELETE operation fails due to exection at any stage
Boolean result = false;
try (
//Objects that can automatically be closed at the end of the TRY block
//This is known as AutoCloseable
Connection dbConnection = getDBConnection();
PreparedStatement statment = dbConnection.preparedStatement(DELETE_QUERY))
{
//replace ? with Tag
statement.setString(1, Tag);
int row = preparedStatement.executeUpdate();
//If statement fails skip to catch block
result = true;
System.out.println("The record in row " + row + " has been deleted successfully");
} catch (SQLException sqle) {
//likely thrown due to "Record Not Found"
//TODO investigate further for the specific exception thrown from the database implementation you are using.
//TODO print helpful message to help user of this method resolve this issue
} catch (Exception) {
//TODO handle any other exceptions that may happen
}
return result;
}
}
I have users table in MySQL and I created a stored procedure so that when get username and password from swing textfields passed them into stored procedure and learn if is there exist that user to login, but I can not get resultset actually in phpMyAdmin stored procedure work properly but in netbeans can not get resultset and runtime never stop in console , running always.
I do not think there is a problem in my code somewhere else because it is so simple code.
Here is my stored procedure in MySQL
SELECT * FROM `users` WHERE `users`.`E-Mail` = #p0 AND `users`.`Password` = #p1
it takes two parameter varchar and I tried before those as a text
Here is the specific part of my java code
public void loginPass(String email, String password){
try {
DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/askdocdb","root","");
CallableStatement mystatement = connection.prepareCall("{CALL sp_Login (?, ?)}");
mystatement.setString(1, email);
mystatement.setString(2, password);
// mystatement.setString("#p0", email);
// mystatement.setString("#p1", password);
boolean situation = mystatement.execute();
System.out.println(situation);
// resultset = mystatement.executeQuery();
resultset = mystatement.getResultSet();
String res = resultset.getString(2);
System.out.println(res);
// resultset = mystatement.executeQuery();
while(resultset.next()){
System.out.println("asdsad");
}
resultset.close();
} catch (Exception e) {
}
}
The reason of comment lines, I tried any possible combination of syntax
situation returns true
res does not return
and can not enter into while statement
Thank you for your support and comments already now.
It's difficult to say what exactly is wrong with your code as there are quite a few possible points for failure if you choose to use a stored procedure for this simple task (incorrect syntax in the procedure, problems with getting the return value over JDBC, etc). I would simply run the SQL query over JDBC for checking the credentials:
public void registerDriver() {
try {
DriverManager.registerDriver((Driver) Class.forName(
"com.mysql.jdbc.Driver").newInstance());
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
throw new RuntimeException("Could not register MySQL driver!", e);
}
}
public boolean checkLogin(String email, String password) {
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/askdocdb", "root", "");
PreparedStatement ps = connection
.prepareStatement("SELECT 1 FROM users WHERE "
+ "E-Mail = ? AND Password = ?")) {
ps.setString(1, email);
ps.setString(2, password);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return true; // username and password match
} else {
return false; // no row returned, i.e. no match
}
}
} catch (SQLException e) {
throw new RuntimeException(
"Error while checking user credentials!", e);
}
}
What was changed:
JDBC driver registration has been extracted into a separate method (registerDriver()), which you only need to call once (e.g. after the program has started), not each time you check for credentials.
Resources such as Connection, PreparedStatement and ResultSet are now being closed properly (even if an exception is thrown) because they are declared through the try-with-resources statement.
The method now returns a boolean that corresponds to whether the credentials were valid or not, making it easier to use from calling code.
Exceptions that cannot be handled (e.g. SQLException) are rethrown as RuntimeExceptions (instead of just swallowing them in an empty catch block).
Basically, when an SQLException is thrown, either there is a programming error in the code (invalid query syntax) or something severely wrong with the database. In either case, the only option is usually to halt your program. You can declare throws SQLException in the method signature if you'd want to handle the situation in the calling method instead.
Finally, it needs to be mentioned that you should never store passwords in the database as plain text, to avoid anyone with read access to the db to login as an arbitrary user. Instead, you should store password hashes, or even better, salted hashes. More on this e.g. in Best way to store password in database.
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
I need to insert some data into a table. When program executes to insert, there may arise an error because I haven't created the table. I would like to create that table in a catch block and return to try block. So whenever the table is deleted or happens to delete, the try catch will build the table.
I have written some code for it, but it fails.
import java.sql.*;
/**
*
* #author JOJO
*/
public class ConnectDB {
static Connection conn;
static String driver = "org.apache.derby.jdbc.ClientDriver";
static String connectionURL = "jdbc:derby://localhost:1527/Libraryprj;user=scott;password=tiger";
public void AddBookDB(String bookName) throws SQLException {
String createString = "CREATE TABLE BOOKLEDGER (BOOKNAME VARCHAR(50) NOT NULL)";
try {
Class.forName(driver);
} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try
{
conn = DriverManager.getConnection(connectionURL);
Statement stmt = conn.createStatement();
boolean execute = stmt.execute("insert into BOOKLEDGER values ('" + bookName + "')");
stmt.close();
}
catch (SQLException sqlExcept)
{
Statement stmt = (Statement) conn.createStatement();
stmt.executeUpdate(createString);
sqlExcept.printStackTrace();
}
}
}
From my point of view it is better to proceed in another way(use control structure instead of try-catch), so you can test before if the table exist in this way :
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "table_name", null);
if (!rs.next()) {
//Table not Exist, let's create it
}
//Insert data into the table ...
It is a bad practice using try-catch in a similar case, try catch construct should be used only to catch exceptional situation, not in place of a control structure ...
It's an extra query, but i allways use this solution:
Connection connection = DriverManager.getConnection(...) // create the connection
Statement statement = connection.createStatement(...)
And use this query, to make sure that the table exists. It can only fail, if someone deletes your table while your following java code runs...
statement.execute("CREATE TABLE IF NOT EXISTS yourtable(...Your schema...)");
After this point you can assume that the table exists, and work with it, without expecting any seroius issue
The major problem with your approach is that you are catching the generic SQLException, which may have occurred for a very wide variety of reasons, your assumed reason being only one of them. That is why it is much more appropriate to test explicitly for the condition of table non-existence before trying to create it.
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