I have this method here - whenever I comment out the MySQL section, from String query to pst.close() - the code works fine. However, if I don't, then it gives me the error of Connection Reset. I am using a socket between a client and a server for your information. How would I fix this? Or it it a problem that does not deal with MySQL?
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
Connection connection = establishConnection();
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
String query = "insert into test(`username`, `password`, `email`, `fullname`) values (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered!";
}
return returnStatement;
}
You should probably have a connection.close() before the return.
Or, if you are in a relatively new version of JRE, you could possibly achieve the same with try-with-resource.
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
try (Connection connection = establishConnection()) {
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
String query = "insert into test(`username`, `password`, `email`, `fullname`) values (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered!";
}
}
return returnStatement;
}
This will ensure that your connection closes when the try block finishes. However, that would require that the Connection class implements the AutoCloseable interface.
I think the connection is getting established and not getting closed, might be the issue.
Here is what works for me, as suggested by #Binaek Sarkar (I modified it a little bit):
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
try {
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
Connection connection = null;
connection = MySQLConnection.dbConnector();
String query = "INSERT INTO `test`(`username`, `password`, `email`, `fullname`) VALUES (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered! You will redirected to the login page now. ";
}
}catch(Exception e) {returnStatement = "Invalid. Please try again!";}
return returnStatement;
}
Related
String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
public void createConnection(int id, String name, String author, String
publisher) {
try {
Connection mycon = DriverManager.getConnection(dburl);
Statement mystmt = mycon.createStatement();
String sql = "insert into addbook" + "(Book ID,Book
Name,Author,Publisher)" + "values" + "(" + id + "," + name + "," +
author + "," + publisher + ")";
mystmt.executeUpdate(sql);
System.out.println("updated");
} catch (Exception ex) {
}
execute update is a method in another class.there seem to be
whats the wrong with this code segment? database is not updating!!
You have not loaded the database drivers, to do that include this code:
Class.forName("com.mysql.jdbc.Driver");
If you haven't drivers download and put in project library.
Their are some problems with this code snippet. One is you didn't load the database. Also you didn't use the username and password.
I recommend you to create the database connection separately. Maybe in a separate Java file. As below,
public class DatabaseConnection {
public static Statement getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver"); //Loading the database
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3307/restaurentsystem","nandika","nandika"); //username and password can save as variables and pass here
Statement statement = c.createStatement();
return statement;
}
}
Then you can use it whenever you want. In this situation,
try {
Statement s = DatabaseConnection.getConnection();
s.executeUpdate("INSERT INTO addbook (Book ID, Book Name, Author, Publisher) VALUES (?, ?, ?, ?);"); //Values should assign here.
System.out.println("updated");
} catch (Exception e) {
System.out.println(e);
}
This is what I do if I do this. I recommend you to try this method.
This is the way you should be doing it, with preparedStatement to prevent injections
String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
private PreparedStatement preparedStatement;
private Connection con = null;
public static void main(String[] args) {
}
public void createConnection(int id, String name, String author, String publisher) {
try {
con = DriverManager.getConnection(dburl, user, password);
String stmt = "INSERT INTO addbook (Book ID,Book Name,Author,Publisher) VALUES (?, ?, ?, ?)";
preparedStatement = con.prepareStatement(stmt);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, author);
preparedStatement.setString(4, publisher);
preparedStatement.executeUpdate();
con.close();
System.out.println("updated");
} catch (Exception ex) {
}
Please help me fix the error in this program. The problem is, even if I use the correct username and password, I can't create a verified login.
public class LoginDao {
public static boolean CheckUser(String Username,String Password)
{
boolean st =false;
String dbUsername, dbPassword;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DBConnection.getConnection();
String qry ="select *user where Username=? and Password=?";
PreparedStatement pst = con.prepareStatement(qry);
//pst.setString(1, Username);
//pst.setString(2, Password);
pst.executeQuery(qry);
ResultSet rs = pst.getResultSet();
while(rs.next()){
dbUsername = rs.getString("Username");
dbPassword = rs.getString("Password");
if(dbUsername.equals(Username) && dbPassword.equals(Password)){
System.out.println("Welcome");
st = true;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Check your SQL query? You are missing a FROM before * and user. Also you need to set the parameters when using a PreparedStatement, you have them commented out.
UPDATE
Try this:
public class LoginDao {
public static boolean CheckUser(final String username, final String password) {
final String qry ="SELECT * FROM user WHERE Username=? AND Password=?";
Connection con = null;
PreparedStatement pst;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DBConnection.getConnection();
pst = con.prepareStatement(qry);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery(qry);
rs = pst.getResultSet();
// Notice I changed the 'while' by 'if'
if (rs.next()) {
return (username.equals(rs.getString("Username")) && password.equals(rs.getString("Password")));
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
// close/release (database resources) 'con', 'pst', 'rs' here
}
return false;
}
}
I tried to insert some data from java to my database (ms.access) but when I click button nothing add to database. here is the code:
private void EmpButtonMouseClicked(java.awt.event.MouseEvent evt) {
String name,sex,email,username,password;
name = tfName.getText();
sex=(String) cbSex.getSelectedItem();
email=tfEmail.getText();
username=tfUser.getText();
try{
String url;
url = "jdbc:odbc:mydata";
Connection conn = DriverManager.getConnection(url,"","");
Statement stm = conn.createStatement();
stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
conn.close();
}catch (SQLException sqlException){}
}
what wrong with that code?
I think I found the way to do it...
String sex=(String) cbSex.getSelectedItem();
try{
String url = "jdbc:odbc:mydata";
Connection conn = DriverManager.getConnection(url,"","");
String sql = "INSERT INTO CustomerLogin(Name, Email, Sex, Username, Password) VALUES(?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, tfName.getText());
pst.setString(2, tfEmail.getText());
pst.setString(3, sex);
pst.setString(4, tfUser.getText());
pst.setString(5, pfPassword.getText());
pst.execute();
tfName.setText("");
tfEmail.setText("");
tfUser.setText("");
pfPassword.setText("");
JOptionPane.showMessageDialog(null,"Succed Create Account! You can now return to Login Page");
}catch (Exception e){
JOptionPane.showMessageDialog(null,e); }
The Problem is :
stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
write like :
stm.executeUpdate("INSERT INTO EmployeeLogin VALUES ("+name+", "+email+", "+sex+", "+username+")");
Hi I have this method below which should insert values into my database. However I am getting a Null Pointer Exception on the PreparedStatement line
public void insertReservation(String name, String phone, int size, String date, String time, String additionalRequirements, String memberID, String themeID) throws SQLException, ClassNotFoundException {
try {
String strQuery = "INSERT INTO reservation VALUES (?, ? ,?, TO_DATE(?, 'dd-MMM-yy'), ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(strQuery);/
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setInt(3, size);
stmt.setString(4, date);
stmt.setString(5, time);
stmt.setString(6, additionalRequirements);
stmt.setString(7, memberID);
stmt.setString(8, themeID);
results = stmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}//end try
}
Am I inserting this correctly into my database? I am not sure why I am getting this null pointer exeception error.
conn is null, print its value.
Don't know but try this
String strQuery = "insert into reservation(ColumnName1, ColumnName2 ,ColumnName3,) values(?,?,?)";
and at the end it will be only execute();
like this stmt.execute();
executeQuery(); statement works with select query Only
Secondly have you described conn value in constructor or method in which ever class you are using the query if you have than assign it like this conn= SqlConnection.ConnecrDb();
below is the SqlConnection Seperate class i have created
public class SqlConnection {
Connection conn=null;
public static Connection ConnecrDb(){
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn= DriverManager.getConnection("jdbc:odbc:Test","","");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Hope it will help you
How can I detect the empty result set sending from MySQL if there is no possible result.
Just check if ResultSet#next() returns true. E.g.
public boolean exist(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
close(resultSet, statement, connection);
}
return exist;
}
which you can use like follows
if (userDAO.exist(username, password)) {
// Proceed with login?
} else {
// Show error?
}
Alternatively, you could also let it return a fullworhy User or null if there's none. E.g.
public User find(String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, username, email, dateOfBirth FROM user WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User(
resultSet.getLong("id"),
resultSet.getString("username"),
resultSet.getString("email"),
resultSet.getDate("dateOfBirth"));
}
} finally {
close(resultSet, statement, connection);
}
return user;
}
with
User user = userDAO.find(username, password);
if (user != null) {
// Proceed with login?
} else {
// Show error?
}