I am trying to access a variable from one class in another.
In my example below, I have 2 files, one called login.java and usermainpage.java.
I want to access a variable called sessionId that is in login.java from usermainpage class file.
I tried several methods but it is not working at all, in login class file, I declared sessionId as a public string and in the file I define it as equals to a data that I retrieved from my database. (If you see the code I am doing a database connection also).
I thought by returning sessionId at the end of the function I can now access this variable from all other java files but no, in my usermainpage.java file, I tried printing out sessionId and it displays nothing. Let me know of a solution, thank you.
// login.java file
public class login extends javax.swing.JFrame {
public String sessionId;
Connection con;
PreparedStatement pst;
ResultSet rs;
private String LoginButtonActionPerformed(java.awt.event.ActionEvent evt) {
try{
String query = "SELECT * FROM `accounts` WHERE username=? and password=?";
con = DriverManager.getConnection("jdbc:mysql://localhost/restock", "root", "password");
pst = con.prepareStatement(query);
pst.setString(1, txtUsername.getText());
pst.setString(2, txtPassword.getText());
rs = pst.executeQuery();
if(rs.next()){
String userType = rs.getString("usertype");
sessionId = rs.getString("id");
System.out.print("##########" + sessionId + "##########"); //this prints out the id I want
if(userType.equals("Admin")){
JOptionPane.showMessageDialog(this, "Login is successful as admin");
mainpage admin = new mainpage();
admin.setVisible(true);
dispose();
} else{
JOptionPane.showMessageDialog(this, "Login is successful as user");
usermainpage user = new usermainpage();
user.setVisible(true);
dispose();
}
}
else{
JOptionPane.showMessageDialog(this, "Incorrect username or password");
txtUsername.setText("");
txtPassword.setText("");
}
} catch(HeadlessException | SQLException ex){
JOptionPane.showMessageDialog(this, ex.getMessage());
}
return sessionId;
}
}
//usermainpage.java file
public class usermainpage extends javax.swing.JFrame {
private void RequestButtonActionPerformed(java.awt.event.ActionEvent evt) {
String type = txttype.getSelectedItem().toString();
String name = txtname.getText();
String quantity = txtquantity.getText();
String status = "Pending";
String userId;
//Create new class object from login.java
login testing = new login();
userId = testing.sessionId;
System.out.print("########## " + userId + "########## "); //this prints out null value
}
}
EDIT: These are some of the problems I encountered based on the suggestions.
There are so many problems with your code:
You should always follow Java naming conventions e.g. you should name your class as Login instead of login. Similarly, the name of your method should be loginButtonActionPerformed instead of LoginButtonActionPerformed.
I do not see any use of the parameter, java.awt.event.ActionEvent evt in your method, LoginButtonActionPerformed. I would remove it from its definition and the calls.
You should avoid making variables public. You should keep sessionId as private or protected as per the requirement and create the public accessor and mutator for it as shown below:
private String sessionId;
public setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getSessionId() {
return sessionId;
}
You are returning the value of sessionId from the method, LoginButtonActionPerformed and therefore you need to call this method inside your method, RequestButtonActionPerformed as follows:
login testing = new login();
userId = testing.LoginButtonActionPerformed(evt);
However, for this, you need to declare your method, LoginButtonActionPerformed as public.
A better approach would be to declare LoginButtonActionPerformed as public void and then you can do:
login testing = new login();
testing.LoginButtonActionPerformed(evt);
userId = testing.getSessionId();
Related
I am trying to get my code to check if my username and password are in the database only I have errors everywhere. Do you have a solution?
here my code in my Login_form :
PreparedStatement st;
ResultSet rs;
// donnez l'username et le password
String username = jTextField_Username.getText();
String password = String.valueOf(jPasswordField.getPassword());
// requete indiquant si les identifiants existent
String query = "SELECT * FROM 'users' WHERE 'username' = ? AND 'password' = ?";
try {
st = Connecter.getConnection().prepareStatement(query)
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if(rs.next())
{
// Show my new form
}else{
// Error message
}
} catch (SQLExeption ex) {
Logger.getLogger(Login_Form.class.getName()).log(Level.SEVERE, null, ex);
}
and this is my code of my connector
package javaapplicationhotel2;
import java.sql.*;
public class Connecter {
static Object getConnection() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Connection con;
public Connecter() {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
}catch(ClassNotFoundException e){
System.err.println(e);
}
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hotel","root","");
}catch(SQLException e){System.err.println(e);}
}
Connection obtenirconnexion(){return con;}
PreparedStatement prepareStatement(String select__from_classe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
The Problem seems to reside in your Connecter class. Especially in the getConnection() and prepareStatement() methods since they always return throwing an UnsupportedException. Another issue is that getConnection() is of the return type Object, even though you treat it as a Connector in your try block. Therefore I'd suggest you changing getConnection's return type to Connection and returning a new Connection() or using new Connection() in the first place. Also you may want to replace your setString(int, String) calls, which presumably replace the '?' with the corresponding username and password, with String.format(String, Object...). You can use this method to replace certain parts of a String (eg. %s for Strings, %d for Integer, etc.) So in your case you would use it as the following:
String format = "SELECT * FROM 'users' WHERE 'username' = %s AND 'password' = %s;"
String query = String.format(format, username, password);
As a side note:
In modern jdbc you are actually not required to load the Driver class with Class.forName(String), so you may omit it.
One last thing:
It'd be nice if you could indent your code appropriately the next time, since that would make understanding it a lot easier.
I'm trying to functionality to login with credentials from the database. So far I've just been getting an EJBTransactionRolledbackException. The stack trace is huge and so far I have not been able to find anything online related to my specific issue.
So the MySQL database I have set up has tables divided up into logical data. I have a user_info table with a memberID, addressID, loginID, firstName, lastName, email, phoneNumber, and isModerator. My user_login table has loginID, username, and password. The user_address table is not necessary at this point in the program. The loginID from the user_login table is a foreign key in the user_info table. So I essentially do an inner join to get all the info from bot tables and then try to create a new user object and return it. I've tried just pulling data from one table but the same issue persists. The query being used in the Java code works just fine in MySQL workbench.
Here is the method in question, it's the findEntry method:
#Stateless
#Local(DataAccessInterface.class)
#LocalBean
public class UserDataService implements DataAccessInterface<User> {
public UserDataService() {
}
#Override
public List<User> findAll() {
return null;
}
#Override
public User findEntry(String condition) {
String query = "SELECT * FROM user_info INNER JOIN user_login WHERE username='" + condition + "';";
Connection databaseConnection = null;
Statement statement = null;
ResultSet resultSet = null;
User currentUser = null;
try {
databaseConnection = DriverManager.getConnection(url, username, password);
statement = databaseConnection.createStatement();
resultSet = statement.executeQuery(query);
currentUser = new User(resultSet.getInt("memberID"), resultSet.getInt("addressID"), resultSet.getInt("loginID"), resultSet.getString("firstName"), resultSet.getString("lastName"), resultSet.getString("email"), resultSet.getString("phoneNumber"), resultSet.getString("username"), resultSet.getString("password"), resultSet.getInt("isModerator"));
}
catch(SQLException e) {
throw new DatabaseException(e);
}
finally {
try {
if(databaseConnection != null) {
databaseConnection.close();
statement.close();
resultSet.close();
}
}
catch(SQLException e) {
throw new DatabaseException(e);
}
}
return currentUser;
}
Here is where the findEntry is being called:
#Stateless
#Local(AccountBusinessInterface.class)
#LocalBean
public class AccountBusiness implements AccountBusinessInterface {
#EJB
private DataAccessInterface<User> userDataService;
public AccountBusiness() {
}
/**
* Validates that the use who entered in their username and password entered the correct information.
*/
#Override
public int validateUser(User user) {
//Sets the login boolean to true.
//user.setLoggedIn(true);
//Sets the login text to logout.
//user.setLoginText("Logout");
User currentUser = userDataService.findEntry(user.getUsername());
if(currentUser != null) {
return 0;
}
return 1;
}
This is the onLogin method in the login controller:
#ManagedBean
#ViewScoped
public class LoginController {
/**
* This is the BusinessAccountInferface.
*/
#Inject
private AccountBusinessInterface accountBusinessInterface;
/**
* The default constructor.
*/
public LoginController() {
}
/**
* Takes in a user object and returns the product page that can only be seen by a logged in user, assuming the correct
* username and password was entered.
* #param user
* #return String
*/
public String onLogin(User user) {
//Gets the user object from the appropriate form.
FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("user", user);
//If authentication fails, returns the error page.
if(accountBusinessInterface.validateUser(user) == 0) {
//Return the products page.
return "ProductsPage.xhtml";
}
//Returns the login page by default.
return "Login.xhtml";
}
Here is my custom exception:
public class DatabaseException extends RuntimeException {
/**
* This is the default serial version id.
*/
private static final long serialVersionUID = 1L;
public DatabaseException() {
printStackTrace();
}
public DatabaseException(SQLException e) {
printMessage(e.getMessage());
}
public DatabaseException(String message) {
printMessage(message);
}
public DatabaseException(SQLException e, String message) {
printMessage(e.getMessage());
printMessage(message);
}
private void printMessage(String message) {
System.err.println(message);
}
}
The stack trace is too long, but here are the first two lines:
19:11:22,668 ERROR [stderr] (default task-18) Before start of result set
19:11:22,671 ERROR [org.jboss.as.ejb3.invocation] (default task-18) WFLYEJB0034: EJB Invocation failed on component UserDataService for method public beans.User data.UserDataService.findEntry(java.lang.String): javax.ejb.EJBTransactionRolledbackException
The rest of the stack trace is in a file here since I couldn't paste it here:
https://www.dropbox.com/s/r4ampjxr7clfzjz/log.txt?dl=0
The expected result is that a user will be returned from the findEntry method, which is checked in the validateUser method on the business logic, and if it does not return null then 0 is returned which is checked in the login controller which should log the user in. Obviously something is wring with the database being rolled back. I'm just not sure what that means or what is causing it to happen or how to fix it. Did I leave any important code or xml files out?
You have to move the curser in the result set first, this is what the error message "Before start of result set" is telling you.
So move the curser first before reading from it. ResultSet#next() will return true if it is not already at the end.
if (resultSet.next()){
currentUser = new User(resultSet.getInt("memberID")...
}
I'm setting up java project where user enter his details and the data will be saved in the the database bellow is my code:
public String CreateUserDetails() throws SQLException, JsonProcessingException
{
iterationResourse = new IterationResourse();
dbcon = DatabaseConnection.getInstance();
iteratinDetails = IterationDetailsParser.getInstance();
try {
String sqlUser = "INSERT INTO user (User_Id,Username,Active_Indi)VALUES(?,?,?)";
PreparedStatement statement = (PreparedStatement) dbcon.con.prepareStatement(sqlUser);
statement.setString(1, iterationResourse.ConvertObjectToString(iteratinDetails.getUserId()));
statement.setString(2, iterationResourse.ConvertObjectToString(iteratinDetails.getUserObj()));
statement.setBoolean(3, true );
statement.executeUpdate();
statement.close();
System.out.println("user created");
st = "user created";
} catch (SQLException e)
{
System.out.println("user id alredy exits");
userIdExits = false;
ObjectMapper mapperUser = new ObjectMapper();
JsonNode rootNode = mapperUser.createObjectNode();
((ObjectNode) rootNode).put("Response", "User ID alreday exits");
String jsonString = mapperUser.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(jsonString);
iterationResourse.response = jsonString;
st = "Response\", \"User ID alreday exits";
}
return st;
}
I have to write a test case for the above code i have tried the fallowing code. i am trying to mock all the objects that i am trying to use form the other class , the expected result should be string that returns "User created" . but i am unable the get the expected result based on the current code.
public class UserDatabaseTest {
User user = null;
IterationResourse iterationResourse;
DatabaseConnection db;
IterationDetailsParser iterationDetails ;
#Before
public void setUp()
{
iterationResourse = mock(IterationResourse.class);
db = mock(DatabaseConnection.class);
iterationDetails = mock(IterationDetailsParser.class);
user = new User();
}
#Test
public void test() throws JsonProcessingException, SQLException {
Object Object = "3";
String value = "3";
when(db.getInstance().GetDBConnection()).thenReturn(db.getInstance().GetDBConnection());
when(iterationDetails.getUserId()).thenReturn(Object);
when(iterationResourse.ConvertObjectToString(Object)).thenReturn(value);
assertEquals(user.CreateUserDetails(), "user created");
}
}
There are two cases to be written here.
CreateUserDetails return "user created"
Else return "User ID already exists" (i fixed the two typos)
As stated in the comments you should really abstract your DAO layer. But at a high level, you want to mock the DatabaseConnection and return mocks for anything it may return. Doing this prevents NPE's when calling your code base.
Once your mocks are in place the test should return "user created". For the second test have one of your mock throw an SQLException and you can test that "User ID already exists" is returned. I would probably just pass iteratinDetails as a parameter, seems like a dependency for this method.
Lastly, you should not be testing that your code has created database tables and populated them correctly. As long as the data you are passing in (which is something you can test) you should have faith that SQL is going to execute scripts as intended. If you really wanted to get crazy, you could do some mocking to ensure that the statement was prepared properly. IMO that's overkill.
Goodluck!
Can someone review my code
This query is fetching two values address_id and postcode from table1. Here
AddressID class has two variable postcode(string) and address_id(integer) :
#Select("SELECT address_id,postcode FROM table1 WHERE custom_field_1 = #{caseid}")
public List<AddressID> getAddressIdPostCodeList(String caseid);
Here is how AddressID looks AddressID.java
private int addressId;
private String postcode;
//getters and setters of Pstcode and addressId
#Override
public String toString() {
return "PostCode : " + this.postcode;
}
while executing this query I get value of address_id as 0 and required postcode. Although DB has values of address_id which is not zero. Where my code is failing?
This is where in my main method I am calling
List<AddressID> addresses = new ArrayList<>();
addresses = mainClassObject.getAddressIdPostCodeList(address.getcaseId());
Ideally addresses object should have both address_id and postcode. I am getting both values but address_id I am getting 0 and correct values for postcode.
Since I cant comment because I dont have 50 reputation, I had to write it here, its hard to tell from the code you posted, to give you an answer I need more detail on what getAddressIdPostCodeList() does, since you said the data in the DB has no ceros the error must be in the method getAddressIdPostCodeList() and/or in how you are handling the resultset of the Query
EDIT: Solution using Oracle JDBC Driver
Since I dont know how to use Mybatis, heres a solution using JDBC.
to connect using JDBC to your Oracle DB here's a simple tutorial:
1. First you need to download de JDBC driver from Oracle depending your DB version (11g,12c,10g), the driver Its called ojdbcX.jar where X is a number of the version of the driver
2. After you have downloaded the driver you need to add the .jar to your project, if you are using Netbeans IDE you can add it like this:
if you are using Eclipse you can use the following Link to see how to add the .JAR file: How to import a jar in Eclipse
3. After adding the .JAR its pretty simple, you just need to connect to the DB using your credentials, here is an example on how to do it:
Connection connection = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system", "password"); } catch (Exception ex) {
ex.printStackTrace();
}
for more deatiled information on how to connect, you can check the oracle.jdbc
Class OracleDriver Documentation
4. After the connection has been made its pretty simple, Heres a short code example to get the result you want, you need to modify it with your connection details and as you see fit because im making a couple of assumptions, this code is just an example:
Main.Java
public class Main {
public static void main(String[] argv) {
List<AddressID> addresses;
SQLConnect conex= new SQLConnect();
String caseid="the id you want";
addresses=conex.getAddressIdPostCodeList(caseid);
}
AddressID.java
public class AddressID {
private String addressId;
private String postcode;
}
SQLConnect.Java
public class SQLConnect {
public static Connection connection;
public SQLConnect (){
createConnection();
}
public void CreateConnection(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system", "password")
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void closeConnection(){
if(connection!=null){
try {
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public ResultSet ExecuteQuery(String queryTXT) throws SQLException{
Statement query = connection.createStatement();
ResultSet table=query.executeQuery(queryTXT);
return table;
}
public List<AddressID> getAddressIdPostCodeList(String caseid) throws SQLException{
List<AddressID> addresses = new ArrayList <> ();
ResultSet table=ExecuteQuery("SELECT address_id,postcode FROM table1 WHERE custom_field_1 ='"+caseid+"';");
while (table.next()) {
AddressID aux;
aux.addressId=table.getString(1);
aux.postcode=table.getString(2);
addresses.add(aux);
}
return addresses;
}
}
I did forgot to wtite my result query which is actually binding data fetched
from select query to the AddressId class..
#Results(id = "result",
value = {
#Result(property = "addressId", column = "address_id"),
#Result(property = "postcode", column = "postcode")
}
)
I have an aplication which create a number of query (update or insert) and then each query is executed.
The whole code is working fine but I've saw that my server IO latency is too much during this proccess.
The code execute a loop which is taking arround 1 minute.
Then what I wanted to do is write each query in memory instead to execute it, and then, once I have the whole list of query to execute, use "LOAD DATA LOCAL INFILE" from mysql, which will take less time.
My question is: How can I write all my query (String object) in a "File" or "any other container" in java to use it after the loop?.
#user3283548 This is my example code:
Class1:
import java.util.ArrayList;
public class Class1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ArrayList<String> Staff=new ArrayList<String>();
Staff.add("tom");
Staff.add("Laura");
Staff.add("Patricia");
for (int x = 0; x < Staff.size(); x++) {
System.out.println(Staff.get(x));
Class2 user = new Class2 (Staff.get(x));
user.checkUser();
}
}
}
Class2:
public class Class2 {
private String user;
public Class2(String user){
this.user=user;
}
public void checkUser() throws Exception{
if (user.equals("tom")){
String queryUser="update UsersT set userStatus='2' where UserName='"+user+"';";
Class3 updateUser = new Class3(queryUser);
updateUser.UpdateQuery();;
}else{
String queryUser="Insert into UsersT (UserName,userStatus)Values('"+user+"','1');";
Class3 updateUser = new Class3(queryUser);
updateUser.InsertQuery();
System.out.println(user+" is not ton doing new insert");
}
}
}
Class3:
public class Class3 {
public String Query;
public Class3(String Query){
this.Query = Query;
}
public void UpdateQuery() throws Exception{
/*// Accessing Driver From Jar File
Class.forName("com.mysql.jdbc.Driver");
//DB Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/default","root","1234567");
String sql =Query;
PreparedStatement pst = con.prepareStatement(sql);*/
System.out.println(Query); //Just to test
//pst.execute();
}
public void InsertQuery() throws Exception{
/*// Accessing Driver From Jar File
Class.forName("com.mysql.jdbc.Driver");
//DB Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/default","root","1234567");
String sql =Query;
PreparedStatement pst = con.prepareStatement(sql);*/
System.out.println(Query); //Just to test
//pst.execute();
}
}
Then, what I wanted to do is create an ArraList in Class1 and use it in Class3 to collect all the queries which has to be executed.
The idea is to execute the list of queries in one time, once the main process is finished, istead to do it for each element within in loop of the Class1. I wanted to do it, because I think it will be take less resource IO from the server HD
Your loop is probably too slow because you're building up Strings using String
I'd hazard a guess you're doing things like
String query = "SELECT * FROM " + variablea + " WHERE + variableb + " = " ...
If you're doing a lot of string concatenation then use StringBuilder as every time you change a string it is actually re-created which is expensive. Simply changing your code to use StringBuilder instead of string will probably cut your loop executed time to a couple of MS. Simply call .toString() method of StringBuilder obj to get the string.
Storing objects
If you want to store anything for later use you should store it in a Collection. If you want a a key-value relationship then use a Map (HashMap would suit you fine). If you just want the values use an List (ArrayList is most popular).
So for example if I wanted to store query strings for later use I would...
Construct the string using StringBuilder.
Put the string (by calling .toString() into a HashMap
Get the query string from the HashMap...
You should never store things on disk if you don't need them to be persistent over application restarts and even then I'd store them in a database not in a file.
Hope this helps.
Thanks
David
EDIT: UPDATE BASED ON YOU POSTING YOUR CODE:
OK this needs some major re-factoring!
I've kept it really simple because I don't have a lot of time to re-write comprehensively.
I've commented where I have made corrections.
Your major issue here is creating objects in loops. You should just create the object once as creating objects is expensive.
I've also corrected other coding issues and replaced the for loop as you shouldn't be writing it like that.I've also renamed the classes to something useful.
I've not tested this so you may need to do some work to get it to work. But this should be a lot faster.
OLD CLASS 1
import java.util.ArrayList;
import java.util.List;
public class StaffChecker {
public static void main(String[] args) throws Exception {
// Creating objects is expensive, you should do this as little as possible
StaffCheckBO staffCheckBO = new StaffCheckBO();
// variables should be Camel Cased and describe what they hold
// Never start with ArrayList start with List you should specific the interface on the left side.
List<String> staffList = new ArrayList<String>();
staffList.add("tom");
staffList.add("Laura");
staffList.add("Patricia");
// use a foreach loop not a (int x = 0 ... ) This is the preffered method.
for (String staffMember : staffList) {
// You now dont need to use .get() you can access the current variable using staffMember
System.out.println(staffMember);
// Do the work
staffCheckBO.checkUser(staffMember);
}
}
}
OLD CLASS 2
/**
* Probably not really any need for this class but I'll assume further business logic may follow.
*/
public class StaffCheckBO {
// Again only create our DAO once...CREATING OBJECTS IS EXPENSIVE.
private StaffDAO staffDAO = new StaffDAO();
public void checkUser(String staffMember) throws Exception{
boolean staffExists = staffDAO.checkStaffExists(staffMember);
if(staffExists) {
System.out.println(staffMember +" is not in database, doing new insert.");
staffDAO.insertStaff(staffMember);
} else {
System.out.println(staffMember +" has been found in the database, updating user.");
staffDAO.updateStaff(staffMember);
}
}
}
OLD CLASS 3
import java.sql.*;
/**
* You will need to do some work to get this class to work fully and this is obviously basic but its to give you an idea.
*/
public class StaffDAO {
public boolean checkStaffExists(String staffName) {
boolean staffExists = false;
try {
String query = "SELECT * FROM STAFF_TABLE WHERE STAFF_NAME = ?";
PreparedStatement preparedStatement = getDBConnection().prepareStatement(query);
// Load your variables into the string in order to be safe against injection attacks.
preparedStatement.setString(1, staffName);
ResultSet resultSet = preparedStatement.executeQuery();
// If a record has been found the staff member is in the database. This obviously doesn't account for multiple staff members
if(resultSet.next()) {
staffExists = true;
}
} catch (SQLException e) {
System.out.println("SQL Exception in getStaff: " + e.getMessage());
}
return staffExists;
}
// Method names should be camel cased
public void updateStaff(String staffName) throws Exception {
try {
String query = "YOUR QUERY";
PreparedStatement preparedStatement = getDBConnection().prepareStatement(query);
// Load your variables into the string in order to be safe against injection attacks.
preparedStatement.setString(1, staffName);
ResultSet resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
System.out.println("SQL Exception in getStaff: " + e.getMessage());
}
}
public void insertStaff(String staffName) throws Exception {
try {
String query = "YOUR QUERY";
PreparedStatement preparedStatement = getDBConnection().prepareStatement(query);
// Load your variables into the string in order to be safe against injection attacks.
preparedStatement.setString(1, staffName);
ResultSet resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
System.out.println("SQL Exception in getStaff: " + e.getMessage());
}
}
/**
* You need to abstract the connection logic away so you avoid code reuse.
*
* #return
*/
private Connection getDBConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/default", "root", "1234567");
} catch (ClassNotFoundException e) {
System.out.println("Could not find class. DB Connection could not be created: " + e.getMessage());
} catch (SQLException e) {
System.out.println("SQL Exception. " + e.getMessage());
}
return connection;
}
}