public static ArrayList<User_Database> getUsername() {
ArrayList<User_Database> list_Username = new ArrayList<User_Database>();
try {
Class.forName(driver);
String sql = "SELECT user_name FROM users";
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
ResultSet rs = state.executeQuery(sql);
while (rs.next()) {
String user_name = rs.getString("user_name");
User_Database userDB = new User_Database(user_name);
list_Username.add(userDB);
System.out.printf(" %s \n", user_name);
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
return list_Username;
}
public static void createNewUser(User_Database us) {
getAllUser();
try {
Class.forName(driver);
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
String sql = "INSERT INTO users VALUES (0, '" + us.user_name + "' , '" + us.user_password + "' , '"
+ us.email + "') ";
if (getAllUser().equals(us.user_name)) {
System.out.println("Username not available");
} else {
state.executeUpdate(sql);
state.close();
System.out.println("Insert Database Success");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
You're calling getAllUser() and I don't know what is does. Let's suppose that you want to call getUsername() instead, which is the method that you present here and that returns all the usernames that you have in your DB in an ArrayList<User_Database>.
When you do if (getAllUser().equals(us.user_name)) you're trying to compare an ArrayList with a String, which is wrong. Please, find the correction to your code bellow:
public static void createNewUser(User_Database us) {
try {
Class.forName(driver);
Connection connect = DriverManager.getConnection(url, user, password);
Statement state = connect.createStatement();
String sql = "INSERT INTO users VALUES (0, '" + us.user_name + "' , '" + us.user_password + "' , '"
+ us.email + "') ";
boolean isUnique = true;
for(User_Database user: getUsername()) {
if(user.user_name.equals(us.user_name)) {
isUnique = false;
break;
}
}
if (!isUnique) {
System.out.println("Username not available");
} else {
state.executeUpdate(sql);
state.close();
System.out.println("Insert Database Success");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
Other notes
Close your statement outside the try catch block, e.g. inside a finally block. This way you ensure that even in the occurence of an exception it will be closed.
Don't forget to close the connection too.
Try to not directly insert the information given by users in your queries, since it can lead to serious problems in your DB (e.g., SQL Injection). Try to see this and use PreparedStatement instead.
Another important consideration:
Since you're checking for the uniqueness of usernames, an ArrayList might not be the best (in terms of performance) to achieve what you want, since you have to go through it when you want to check if there is already a username in your DB or not (O(N)). Instead, try to get all usernames and put them in a HashSet. With set, you just have to try to add the username to it; you will get a true if username is unique or false if it is already in the set (O(1)).
Hope it helped.
Related
As I surfed in many H2 database tutorials it was given that by default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost.
I have created Employee1 table, inserted records and closed the connection. But still I am able to retrieve the Employee1 data if I reconnect the same db after sometime. Why the data still existing?
package connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connector {
static Connection conn = null;
static Statement stmt = null;
public static void main(String[] args) {
System.out.println("Welcome!");
Connector connector = new Connector();
connector.createConnection();
connector.createTable("Employee2");
connector.insertRecord("Employee2");
connector.readRecord("Employee2");
connector.readRecord("Employee1"); //Employee1 Table which is created in previous execution but still it reads the data
connector.closeConnection();
}
public void createConnection() {
try {
System.out.println("Creating connection");
// STEP 1: Register JDBC driver
Class.forName("org.h2.Driver");
// STEP 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:h2:mem/db1", "sa", "");
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
}
public void createTable(String tableName) {
try {
// STEP 3: Execute a query
System.out.println("Creating table in given database with the name of ..." + tableName);
stmt = conn.createStatement();
String sql = "CREATE TABLE " + tableName + "(id INTEGER not NULL, " + " first VARCHAR(255), "
+ " last VARCHAR(255), " + " age INTEGER, " + " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
}
public void insertRecord(String tableName) {
try {
// STEP 3: Execute a query
stmt = conn.createStatement();
String sql = "INSERT INTO " + tableName + " VALUES (500, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO " + tableName + " VALUES (501, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO " + tableName + " VALUES (502, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO " + tableName + " VALUES(503, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
}
public void readRecord(String tableName) {
try {
System.out.println("Reading data from "+tableName);
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM " + tableName;
ResultSet rs = stmt.executeQuery(sql);
// STEP 4: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
// STEP 5: Clean-up environment
rs.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // nothing we can do
} // end try
}
public void closeConnection() {
try {
if (conn != null) {
conn.close();
System.out.println("Connection Closed..");
}
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
}
}
Output of above program:
Welcome!
Creating connection
Connecting to database...
Creating table in given database with the name of ...Employee2
Created table in given database...
Inserted records into the table...
Reading data from Employee2
ID: 500, Age: 18, First: Zara, Last: Ali
ID: 501, Age: 25, First: Mahnaz, Last: Fatma
ID: 502, Age: 30, First: Zaid, Last: Khan
ID: 503, Age: 28, First: Sumit, Last: Mittal
Reading data from Employee1
ID: 400, Age: 18, First: freeze, Last: Ali
ID: 401, Age: 25, First: dora, Last: Fatma
ID: 402, Age: 30, First: xer, Last: Khan
ID: 403, Age: 28, First: kilo, Last: Mittal
Connection Closed..
As you can see here
jdbc:h2:mem/db1
Connects to a local database file with a relative path of mem/db1 so the data still exists because it's saved id a file.
For an in memory database the connection String should be:
jdbc:h2:mem:db1
Notice the difference between / and :
I created the following class in java to make using SQLite easier when I code.
import java.sql.*;
public class Dbm {
//We want to use the connection througout the whole class so it is
//provided as a class level private variable
private Connection c = null;
//This constructor openes or creates the database provided by the arguement
//NameOfDatabase
public Dbm(String NameOfDatabase){
try {
//Database is checked for in project folder, if doesnt exist then creates database
c = DriverManager.getConnection("jdbc:sqlite:" + NameOfDatabase);
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
public void CloseDB(){
try{
c.close();
System.out.println("Closed Database Successfull");
}
catch (Exception e){
System.out.println("Failed to close Database due to error: " + e.getMessage());
}
}
public void ExecuteNoReturnQuery(String SqlCommand){
//creates a statment to execute the query
try{
Statement stmt = null;
stmt = c.createStatement();
stmt.executeUpdate(SqlCommand);
stmt.close();
System.out.println("Sql query executed successfull");
} catch (Exception e){
System.out.println("Failed to execute query due to error: " + e.getMessage());
}
}
// this method returns a ResultSet for a query which can be iterated throughd
public ResultSet ExecuteSqlQueryWithReturn(String SqlCommand){
try{
Statement stmt = null;
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(SqlCommand);
return rs;
}catch (Exception e){
System.out.println("An Error has ocured while executing this query" + e.getMessage());
}
return null;
}
}
Here is the main code in the program
import java.sql.*;
public class InstaText {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Dbm db = new Dbm("people.db");
ResultSet rs = db.ExecuteSqlQueryWithReturn("select * from people;");
try{
String name = "";
int age = 0;
String address = "";
while (rs.isLast() == false){
name = rs.getString("name");
age = rs.getInt("age");
address = rs.getString("address");
System.out.println("Name is " + name +" age is " + age + " Address is " + address);
rs.next();
}
}catch (Exception e ){
System.out.println("Error: " + e.getMessage());
}
db.CloseDB();
}
}
But when I execute it I get the following output:
Opened database successfully
Error: function not yet implemented for SQLite
Closed Database Successfull
So how do I solve the Error "Error: function not yet implemented for SQLite"?
I am running the NetBeans Ide with the latest JDBC on mac os sierra.
Edit: Here is the output after adding e.printstacktrace(); in the catch block:
Opened database successfully
Error: function not yet implemented for SQLite
java.sql.SQLException: function not yet implemented for SQLite
Closed Database Successfull
at org.sqlite.jdbc3.JDBC3ResultSet.isLast(JDBC3ResultSet.java:155)
at instatext.InstaText.main(InstaText.java:24)
The problem is not your select query but the isLast() method you are using on the ResultSet instance to retrieve the result. Try the next() method, it should work :
while (rs.next()){
name = rs.getString("name");
age = rs.getInt("age");
address = rs.getString("address");
System.out.println("Name is " + name +" age is " + age + " Address is " + address);
rs.next();
}
You can read here :
https://github.com/bonitasoft/bonita-connector-database/issues/1
that with SQLLite, you may have some limitations with the isLast() method :
According to JDBC documentation
(http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html)
calls to isLast() and first() methods are forbidden if the result set
type is TYPE_FORWARD_ONLY (e.g SQLite).
I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?
I am trying to update a table using Java JDBC. The method I am using does not throw any errors but the table is not updating. The create table method is below:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CUSTOMERS2 " +
"(PHONE TEXT PRIMARY KEY NOT NULL," +
" SURNAME TEXT NOT NULL, " +
" FIRSTNAME TEXT NOT NULL, " +
" HOME TEXT, " +
" ADDRESS TEXT, " +
" POSTCODE Text)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Customers2 created successfully");
}
The update method is below:
public static void updateCustomers()
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
pstmt = c.prepareStatement(query); // create a statement
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
pstmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully HELLO");
}
I have tried to find some clear instructions on this but cant find any. I do not really understand JDBC and prepared statement very well
When autoCommit is false (c.setAutoCommit(false);), you must manually commit the transaction...
Add...
c.commit()
After pstmt.executeUpdate();
You code also has a flaw, in that if some kind of error occurs during the preparation or execution of the statement, both the Connection and PreparedStatement could be left open, causing a resource leak
If you're using Java 7+ you can use the try-with-resources feature, for example...
try {
Class.forName("org.sqlite.JDBC");
try (Connection c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db")) {
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
try (PreparedStatement pstmt = c.prepareStatement(query)) {
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
c.commit();
}
} catch (SQLException exp) {
exp.printStackTrace();
}
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
System.out.println("Failed to load driver");
}
This will ensure that regardless of how you leave the try block the resource will be closed.
You might also consider taking a look at the JDBC(TM) Database Access
Your update method will set ADDRESS to 1 if there is any row in table with PHONE = does this work.
Try to put Address in 1st Input parameter and Phone 2nd Input parameter
When a connection is created, it is in auto-commit mode.
We need to use [setAutoCommit] method only when we need to make Auto Commit false and make it manual commit after executing the query.
More details at Oracle site on JDBC Transaction.
I'm trying to get a specifc customer id out of a MySQL table from a telephone number input from the user to use it to add a new order to that customer id. I'm trying to use a method that creates a list being filled by resultset but I keep being returned nothing, more specificly empty square brackets "[]"
This is the code im using.
if((getCustomerID.getCustomerID(inputContactNumber).toString()).equals("[]")){
JOptionPane.showMessageDialog(null, "Customer phone number does not exist.\nTry again or create new customer.");
return;
} else {
customerID = Integer.parseInt(getCustomerID.getCustomerID(inputContactNumber).toString());
insertOrder.insertOrder(customerID);
}
getCustomerID():
public List<Customer> getCustomerID(String phoneNumber) throws SQLException{
List<Customer> customerList = new ArrayList();
String selectCustomerID = "SELECT idcustomer FROM customer WHERE contactNumber = " + phoneNumber;
try {
MyConnection mc = new MyConnection();
dbConnection = mc.getConnection();
statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectCustomerID);
while (rs.next()){
int customerID = rs.getInt("idcustomer");
Customer c;
c = new Customer (customerID);
customerList.add(c);
}
}
catch (SQLException e){
System.err.println(e);
return null;
}
finally{
if (statement != null){
statement.close();
}
if (dbConnection != null){
dbConnection.close();
}
}
return customerList;
}//end of getGetCustomerID()
Any input is greatly appreciated
-Edit-
MyConnection()
public class MyConnection {
public Connection connection = null;
public Connection getConnection()
{
System.out.println("---- MySql Connecting ----");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Can't find MySQl Driver.");
e.printStackTrace();
}
System.out.println("Driver Registered.");
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quotedb","root","");
} catch (SQLException e) {
System.out.println("Connection Failed.");
}
if (connection != null) {
System.out.println("Connection Established.");
} else {
System.out.println("Connection Failed.");
}
return connection ;
}
Have you tried executing this query in a SQL Programm? As it looks like simply no result is returned, thus the empty square brackets which is the String equivalent of an empty Array.
toString() on an Array is generally a bad idea, you better use length to determine if the Array is empty. Furthermore it is not clear if the result should be unique or not:
If the function getCustomerID.getCustomerID(inputContactNumber) returns more than one result you try to parse a Int like [3453,3543] which will never be what you want. Instead you should use .get(0) on the Array to retrieve the first element.
Please change your select query to
"SELECT idcustomer FROM customer WHERE contactNumber = '"+phoneNumber+"'"
it will work fine i hope
Change the if condition to:
if(getCustomerID(inputContactNumber) == null || getCustomerID(inputContactNumber).isEmpty()){