So I wanted to read per say 100 lines and print it and it should be happening for every 100 lines and I don't know where to insert that code. The CSV file with one million records isn't getting inserted into the DB as only few thousand are getting inserted.
String csvFilePath = "C:\\Student1.csv";
try {
BufferedReader lineReader = new BufferedReader(new FileReader("C:\\File12\\Student1.csv"));
CSVParser records = CSVParser.parse(lineReader, CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
System.out.println(records.size);
ArrayList<TestSql> students = new ArrayList<TestSql>();
for (CSVRecord record : records) {
TestSql testsql = new TestSql();
testsql.setDate(record.get(0));
testsql.setName(record.get(1));
testsql.setGender(record.get(2));
students.add(testsql);
}
PreparedStatement statement = null;
Connection con = dbconnection();
String sql = "INSERT INTO test12(DOB, NAME, GENDER) VALUES (?, ?, ?)";
statement = con.prepareStatement(sql);
for (TestSql record : students) {
statement.setString(1, record.getDate());
statement.setString(2, record.getName());
statement.setString(3, record.getGender());
statement.addBatch();
}
statement.executeBatch();
con.commit();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
public static Connection dbconnection() {
Connection connection = null;
try {
System.out.println( "Hello World!" );
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/newschema1", "root", "12345");
System.out.println("connection sucessfull");
connection.setAutoCommit(false);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
If you want to insert records from the CSV file into the database table in batches of 100, then you need a counter. In the below code I use a variable count. Whenever it reaches 100, the code inserts those 100 rows and resets the count variable.
Note: More explanations after the code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
public class CsvParse {
private static final int LIMIT = 100;
public static Connection dbConnection() throws SQLException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/newschema1",
"root",
"12345");
connection.setAutoCommit(false);
return connection;
}
public static void main(String[] args) {
try (BufferedReader lineReader = new BufferedReader(new FileReader("C:\\File12\\Student1.csv"))) {
CSVParser records = CSVParser.parse(lineReader,
CSVFormat.EXCEL.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
String sql = "INSERT INTO test12(DOB, NAME, GENDER) VALUES (?, ?, ?)";
Connection con = dbConnection();
PreparedStatement statement = con.prepareStatement(sql);
int count = 0;
for (CSVRecord record : records) {
count++;
if (count > LIMIT) {
count = 1;
statement.executeBatch();
con.commit();
statement.clearBatch();
}
statement.setString(1, record.get(0));
statement.setString(2, record.get(1));
statement.setString(3, record.get(2));
statement.addBatch();
}
// Insert last batch that may be less than LIMIT.
statement.executeBatch();
con.commit();
con.close();
records.close();
}
catch (IOException | SQLException e) {
e.printStackTrace();
}
}
}
In method dbConnection(), I removed Class.forName() since it is no longer needed. I also changed the exception handling. If the method fails to obtain a database connection then there's not much point in continuing since you won't be able to insert anything into the database and that's the whole point of the program. So catching the SQLException in method dbConnection() and printing the stack trace means that when you try to create a PreparedStatement, you will get a NullPointerExcetion since con will be null.
In method main I use try-with-resources when creating lineReader.
I don't see the reason for class TestSql. You can simply set the PreparedStatement parameters directly from the CSV record.
Since Java 7 there is multi-catch so no need for a separate catch block for each exception when each catch block simply prints the stack trace.
I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful
Hello guys so I have this simple java to do and I am trying to connect to an sqlite database from eclipse but it doesn't work at all.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnection {
private String pathDB="C:\\sqlite\\test.db";
private Connection connection=null;
private Statement statement=null;
public DatabaseConnection(String path){
pathDB= path;
}
public void connect () {
try {
Class.forName("org.sqlite.JDBC");
connection= DriverManager.getConnection("jdbc:sqlite:" + pathDB);
statement= connection.createStatement();
System.out.println("Connection to " + pathDB + " "+ "successful");
} catch (ClassNotFoundException notFoundException) {
notFoundException.printStackTrace();
System.out.println("Connection Error!");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.out.println("Connection Error!");
}
String query="Insert into Identity values(0,'issam','issam#mail.com')";
try {
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the main class:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DatabaseConnection connection= new DatabaseConnection("test.db");
connection.connect();
connection.close();
}
}
So I have this sqlite database but whenever I run the code it always gives me : Connection to "path" was successful, no matter what path I put...
I think I have done everything correctly, I downloaded the sqlite JDBC file and added it:
enter image description here
I tried adding a new row to a database table, but it always gives me this:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
at org.sqlite.core.NativeDB.throwex(NativeDB.java:397)
at org.sqlite.core.NativeDB._exec(Native Method)
at org.sqlite.jdbc3.JDBC3Statement.executeUpdate(JDBC3Statement.java:116)
at com.issam.iamcore.DatabaseConnection.connect(DatabaseConnection.java:41)
at com.issam.iamcore.Main.main(Main.java:10)
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
at org.sqlite.core.DB.newSQLException(DB.java:890)
at org.sqlite.core.CoreStatement.internalClose(CoreStatement.java:109)
at org.sqlite.jdbc3.JDBC3Statement.close(JDBC3Statement.java:35)
at com.issam.iamcore.DatabaseConnection.close(DatabaseConnection.java:63)
at com.issam.iamcore.Main.main(Main.java:11)
Any help would be appreeciated, thanks !
You have successfully connected to the database, but did not create table Identity before executing insert query, as it says in the stack trace:
Connection to test.db successful
java.sql.SQLException: no such table: Identity
Call this before inserting a row:
String createQuery = "CREATE TABLE Identity (id INT PRIMARY KEY NOT NULL, name TEXT, email TEXT)";
statement.executeUpdate(createQuery);
I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}
I have finally completed my application (Eclipse, GWT, Java, MySQL, Tomcat) and it has been uploaded onto a server (I have someone else uploading the application onto a server). However, there seems to be an issue with the server installation and my code is not sending back any errors.
For instance: when a new account is created the following message is displayed "Your account has been created. Please contact a leader to associate youth members to it." however the database is not updated. It seems that I am not catching an exception correctly.
My code is:
Client side call:
AsyncCallback<User> callback = new CreationHandler<User>();
rpc.createUser(textBoxAccount.getText(), textBoxPassword.getText(), null, null, null, callback);
Server side:
public User createUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password, acc_enabled) " +
"VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
}
catch (SQLException e) {
//do stuff on fail
System.out.println("SQLException createUser 1.");
e.printStackTrace();
user = null;
}
finally {
if (result != null) {
try {
result.close();
}
catch (SQLException e) {
System.out.println("SQLException createUser 2.");
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
}
catch (SQLException e) {
System.out.println("SQLException createUser 3.");
e.printStackTrace();
}
}
}
return user;
}
Client side:
class CreationHandler<T> implements AsyncCallback<User> {
//Create the account.
public void onFailure(Throwable ex) {
Window.alert("RPC call failed - CreationHandler - Notify Administrator.");
}
public void onSuccess(User result) {
Window.alert("Your account has been created. Please contact a leader to associate youth members to it.");
}
}
Any help would be greatly appreciated.
Regards,
Glyn
Hi JonK,
Is this what you mean please?
public User createUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password, acc_enabled) " +
"VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
}
catch (SQLException e) {
//do stuff on fail
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 1.");
e.printStackTrace();
user = null;
}
finally {
if (result != null) {
try {
result.close();
}
catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 2.");
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
}
catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 3.");
e.printStackTrace();
}
}
}
try {
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 4 - commit error.");
e.printStackTrace();
}
return user;
}
This is the updated code with the suggested error handling:
package org.AwardTracker.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.AwardTracker.client.BCrypt;
import org.AwardTracker.client.Account;
import org.AwardTracker.client.AccountAndCubs;
import org.AwardTracker.client.AccountCubAssociation;
import org.AwardTracker.client.AwardAward;
import org.AwardTracker.client.AwardDescription;
import org.AwardTracker.client.AwardStockDtls;
import org.AwardTracker.client.DBConnection;
import org.AwardTracker.client.SectionDetails;
import org.AwardTracker.client.Stock;
import org.AwardTracker.client.User;
import org.AwardTracker.client.ViewData;
import org.AwardTracker.client.YMATask;
import org.AwardTracker.client.YMAwards;
import org.AwardTracker.client.YMandAward;
import org.AwardTracker.client.YMAwardDetails;
import org.AwardTracker.client.YouthMember;
import org.AwardTracker.client.YouthMemberAwards;
import org.AwardTracker.client.YthMmbrSectDtls;
import org.AwardTracker.server.Base64Encode2;
public class MySQLConnection extends RemoteServiceServlet implements DBConnection {
//TODO
// •Use JNDI to bind the data source.
// •Close the connection as soon as its done in finally block.
// •Manage the connection in single class for whole application.
// •Initialise the data source at application start up single time.
// •Store the database configuration outside the JAVA code somewhere in properties file or web.xml.
// •Create an abstract class for AsyncCallback that will handle all the failures happened while performing any RPC calls.
// •Extend this abstract class for all RPC AsyncCallback but now you have to just provide implementation of onSuccess() only.
// •Don't handle any exception in service implementation just throw it to client or if handled then re-throw some meaning full exception back to client.
// •Add throws in all the methods for all the RemoteService interfaces whenever needed.
private static final long serialVersionUID = 1L;
private Connection conn = null;
private String url = "jdbc:mysql://localhost/awardtracker";
private String user = "awtrack";
private String pass = "************";
public MySQLConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
//NEVER catch exceptions like this
System.out.println("Error connecting to database - not good eh");
e.printStackTrace();
}
}
//Store and retrieve data used by Views within the application
//This allows us to securely pass parameters between Views.
private ViewData viewData = null;
public ViewData setViewData(String accountId, String accountLevel,
String ymId, String awId, String adGroup) {
viewData = new ViewData();
viewData.setaccountId(accountId);
viewData.setaccountLevel(accountLevel);
viewData.setymId(ymId);
viewData.setawId(awId);
viewData.setadGroup(adGroup);
return viewData;
}
public ViewData getViewData() {
return viewData;
}
public User authenticateUser(String accID, String userName, String pass, String level, String pack, Integer enabled, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
String stored_hash = null;
try {
ps = conn.prepareStatement(
"SELECT * " +
"FROM at_accounts " +
"WHERE acc_email_address = ?");
ps.setString(1, userName);
result = ps.executeQuery();
while (result.next()) {
user = new User(result.getString(1), result.getString(2), result.getString(3), result.getString(4), result.getString(5), result.getInt(6), result.getDate(7));
stored_hash = result.getString(3);
}
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for authenticateUser.");
e2.printStackTrace();
}
System.out.println("SQLException in authenticateUser.");
e.printStackTrace();
}
if (stored_hash != null) {
if (BCrypt.checkpw(pass, stored_hash)) {
} else {
user = null;
}
}else{
user = null;
}
return user;
}
//Disable or enable Account
public User disableUser(String user, Integer enabled) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(
"UPDATE at_accounts " +
"SET acc_enabled=? " +
"WHERE acc_email_address=?");
ps.setInt(1, enabled);
ps.setString(2, user);
ps.executeUpdate();
conn.commit();
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for createUser.");
e2.printStackTrace();
}
System.out.println("SQLException in createUser.");
e.printStackTrace();
}
return null;
}
public User duplicateUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(
"SELECT * " +
"FROM at_accounts " +
"WHERE acc_email_address = ?");
ps.setString(1, userName);
result = ps.executeQuery();
while (result.next()) {
user = new User(null, result.getString(2), null, null, null, null, null);
}
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for duplicateUser.");
e2.printStackTrace();
}
System.out.println("SQLException in duplicateUser.");
e.printStackTrace();
}
return user;
}
public User createUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
PreparedStatement ps = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password, acc_enabled) " +
"VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
conn.commit();
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for createUser.");
e2.printStackTrace();
}
System.out.println("SQLException in createUser.");
e.printStackTrace();
}
return null;
}
Points to rememeber:
Use JNDI to bind the data source.
Close the connection as soon as its done in finally block.
Manage the connection in single class for whole application.
Initialize the data source at application start up single time.
Store the database configuration outside the JAVA code somewhere in properties file or web.xml.
I have already shared a sample code for ConnectionUtil class that's sole purpose is to manage the connection in single class using JNDI lookup and it can log that how many connections are opened for what time in the application?
Please have a look at below posts:
“Servlet” (server-side) initialization code in GWT
No operations allowed after statement closed
GWT - how to catch an exception correctly?
Create an abstract class for AsyncCallback that will handle all the failures happened while performing any RPC calls.
Extend this abstract class for all RPC AsyncCallback but now you have to just provide implementation of onSuccess() only.
Don't handle any exception in service implantation just throw it to client or if handled then re-throw some meaning full exception back to client.
Add throws in all the methods for all the RemoteService interfaces whenever needed.
Sample code:
// single class to handle all the AsyncCallback failure
public abstract class MyAsyncCallback<T> implements AsyncCallback<T> {
#Override
public void onFailure(Throwable caught) {
// all the failure are catched here
// prompt user if needed
// on failure message goes to here
// send the failure message back to server for logging
}
}
// do it for all the RPC AsyncCallback
public class CreationHandler<T> extends MyAsyncCallback<T> {
//Create the account.
public void onSuccess(T result) {
// on success message goes to here
}
}
// use in this way
AsyncCallback<User> callback = new CreationHandler<User>();
You aren't committing the transaction to the database. In order for the changes made by ps.executeUpdate(); to become permanent, you will need to call conn.commit(); after the update.
Similarly, in your catch block you should call conn.rollback(); so as to avoid the possibility of dud data being inserted into the database.
I can't see the declaration for conn, so I assume it's a member variable whatever class createUser belongs to. You might want to consider changing the Connection to be a local in the method, so that you don't forget to close it once it's no longer needed (which should be once you've committed).
Lastly, if you're using Java 7+, you can take advantage of try-with-resources to handle the closing of your PreparedStatement, ResultSet and Connection for you (although you don't appear to be using the ResultSet for anything, so consider removing it from the method).
Here are two examples of what I meant (one for Java 6 and below, and one for Java 7 and later utilising try-with-resources:
Java 6-
public void createUser(String userName, String pass) {
PreparedStatement ps = null;
Connection conn = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
// Acquire a Connection here rather than using a member variable
// NOTE: See Braj's answer for a better way of doing this
// using his ConnectionUtil class.
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/awardtracker", "awtrack",
"**************");
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password,"
+ " acc_enabled) "
+ "VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e2) {
System.out.println("Error rolling back transaction.");
e2.printStackTrace();
}
System.out.println("SQLException createUser 1.");
e.printStackTrace();
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
System.out.println("SQLException createUser 3.");
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("Error closing Connection.");
e.printStackTrace();
}
}
}
}
Java 7+
private static final String INSERT_STATEMENT =
"INSERT INTO at_accounts (acc_email_address, acc_password, "
+ "acc_enabled) VALUES (?, ?, ?)";
public void createUser(String userName, String pass) {
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
// NOTE: See Braj's answer for a better way of getting Connections.
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/awardtracker", "awtrack",
"**************");
PreparedStatement ps = conn.prepareStatement(INSERT_STATEMENT);) {
try {
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e2) {
System.out.println("Error rolling back transaction.");
e2.printStackTrace();
}
System.out.println("SQLException createUser 1.");
e.printStackTrace();
}
} catch (SQLException e) {
System.out.println("Error connecting to DB.");
e.printStackTrace();
}
}
In both examples I have removed unused method parameters (why have them there if you're doing nothing with them?) and have changed the return type to void. I did this because in its current form your method will always return null (you initialise your User object to null, then do nothing with it to change its value, then return it at the end).
You should also consider using a logging framework such as log4j to handle your exception logging rather than relying on printStackTrace(). See Why is exception.printStackTrace() considered bad practice? for more information on why printStackTrace() isn't recommended.