ActionPerformed SignUp Query database - JAVA GUI - java

i just wanna ask you about what's wrong about my code..
Here's my code..
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnsubmit){
String Id= String.format("U%03d", countData);
String query="INSERT INTO MsUser(UserID, Username, UserPass, UserFullName, UserEmail, UserPhone, UserAddress, UserGender, Role) VALUES('"+Id+"','"+txtuser.getText()+"','"+txtpass.getText()+"','"+txtname.getText()+"','"+txtemail.getText()+"','"+txtphone.getText()+"','"+txtadd.getText()+"')";
con.executeUpdate(query);
countData=1;
}else{
System.exit(0);
}
and I want if i press submit button, the registration form input to my database.. What should I do? I already had Connect class too..
Here's my connect class code..
public ResultSet executeQuery(String query) {
try {
rs = st.executeQuery(query);
rsm = rs.getMetaData();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Error Connection RS");
}
return rs;
}
public void executeUpdate(String query){
try {
st.executeUpdate(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My database use .mdb, in it has UserID, Username, UserPass, UserFullName, UserEmail, UserPhone, UserAddress, UserGender, Role in MsUser Table..
Is it something missing? I'm sorry about my bad english, I wish u guys can understand what I mean..

Related

How to solve java.lang.String cannot be cast to java.sql.Date?

I want to get the selected row from my JTable and update my database with the information, which was written in the textfields (from the user).
Error message:
"Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.Date"
Code:
int i = tableUsers.getSelectedRow();
if(i>=0) {
try {
boolean IstWirtBoolean;
Date GeburtsdatumDate;
try {
GeburtsdatumDate = new SimpleDateFormat("yyyy-MM-dd").parse(textFieldGeburtsdatum.getText());
if (textFieldWirt.getText().equals("true")) {
IstWirtBoolean = true;
System.out.println((java.sql.Date)(model.getValueAt(i, 5)));
connect.UpdateUser((Integer.parseInt(model.getValueAt(i, 0).toString())),textFieldBenutzername.getText(), textFieldPasswort.getText(),
textFieldName.getText(), textFieldVorname.getText(), new java.sql.Date(GeburtsdatumDate.getTime()),
IstWirtBoolean);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Error at:
"new java.sql.Date(GeburtsdatumDate.getTime())"
How can I solve the error? I already transformed the String into a Date and use the java.sql.Date. What I am doing wrong?
Edit: database code:
public void UpdateUser(int ID,String Benutzername,String Passwort,String Name,String Vorname,Date Geburtsdatum,Boolean IstWirt) throws SQLException {
try {
String query = "Update user set Benutzername=?,Passwort=?,Name=?,Vorname=?,Geburtsdatum=?,IstWirt=? WHERE ID=?";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, Benutzername);
stmt.setString(2, Passwort);
stmt.setString(3, Name);
stmt.setString(4, Vorname);
stmt.setDate(5, Geburtsdatum);
stmt.setBoolean(6, IstWirt);
stmt.setInt(7, ID);
stmt.executeUpdate();
}
catch(Exception e) {
System.out.println(e);
}
}

Why I am getting "oracle.jdbc.driver.OracleResultSetImpl#3ee82600" value in ResultSet instead Userid and password

I've the below DAO method:
public boolean validate(String UserName,String password) throws Exception
{
this.userName=UserName;
this.password=password;
boolean status=false;
PreparedStatement pst = null;
ResultSet rs = null;
Connection con = null;
DataBase db =new DataBase();
con=db.dbConnection();
User user=new User();
try {
pst=con.prepareStatement("select * from login where userId=? and password=?");
pst.setString(1, user.getUserName());
pst.setString(2, user.getPassword());
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
rs=pst.executeQuery();
System.out.println("Result in Resultset"+rs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while(rs.next())
{
if((rs.getString("USERID")==user.getUserName()) && (rs.getString("Password")==user.getPassword()))
{
status=true;
}
else
{
status=false;
}
}
} catch (SQLException e) {
System.out.println("Data is not store in result set");
e.printStackTrace();
}
return status;
}
so here is the problem I am facing in the image I am getting this-"oracle.jdbc.driver.OracleResultSetImpl#3ee82600" value in ResultSet object rs, instead of userid and password from my database
You can get the values of Userid and password by doing
if(rs.next()) {
String userId = rs.getString("userId");
String password = rs.getString("password");
}

Fail to retrieve data from postgresql

this is my connection string for connection postgresql database .And using this code I am able to connect the db
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5433/Test", "youtube",
"1");
Then I am using the same code to retrieve some data .And I get this exception
org.postgresql.util.PSQLException: ERROR: "userdetail" NOT EXIST
Position: 27
which referr this line
con=GetDbConn();
So mytable name is UserDetail not userdetail I dont understand why am i getting this exception message
And this is my code
public class DbUtils {
private static final String DB_DRIVER="org.postgresql.Driver";
private static final String DB_CONN="jdbc:postgresql://127.0.0.1:5433/Test";
private static final String DB_USER="youtube";
private static final String DB_PASS="1";
public void SelectUserDetails() {
Connection con=null;
Statement statement;
String query="select isim,soyisim from UserDetail";
try {
con=GetDbConn();
statement= con.createStatement();
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next()){
String isimM=resultSet.getString("isim");
String soyisimM=resultSet.getString("soyisim");
System.out.println("isim :"+soyisimM+" soyisim: "+soyisimM);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static Connection GetDbConn() {
Connection con = null;
try {
Class.forName(DB_DRIVER);
con=DriverManager.getConnection(DB_CONN, DB_USER, DB_PASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}

Eclipse - GWT - Java - MySQL - how to catch an exception correctly

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.

MYSQL connector saying it has connected even with the wrong username?

I am building a database connection scanner for my security course at university. I have used DriverManager.getConnection(connectionURL, username, password) and it seems to work fine but with one exception that I just cannot understand. If I enter the wrong username it is still returning a connection??? my test code is pasted below. Any pointers would be much appreciated. It returns the correct error if I put the wrong password in, if I turn the server off it tells me. But for some unknown reason it will not tell me if the username is wrong, its as if its not even checking!
public class DBConnector {
Connection connection = null;
String dbURL = "jdbc:mysql://localhost:3306";
String userName;
String password;
public DBConnector() {
// TODO Auto-generated constructor stub
}
public Connection tryConnection(String username, String password){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("Connected");
} catch (InstantiationException e) {
System.out.println("No Connection");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println("Connection Refused");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Sql Ex");
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
}
And here is my main class to run the method.
public class MainTest {
public static void main(String[] args) {
DBConnector dbc = new DBConnector();
dbc.tryConnection("", "");
}
}
Maybe this has something to do with running the test on "Localhost"?
Thanks very much!
I would guess that you are logging in as an anonymous user.
You can make your local MySQL Server installation more secure (and hence force your code above to throw an error) by removing the anonymous user like this:
DELETE FROM mysql.user WHERE user='';
FLUSH PRIVILEGES;
Then try connecting with no username and password.

Categories