Java SQL (JDBC) : how to move to the next column? - java

I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?

Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.

Related

Can't Update the SQL through Java

I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.

cannot set null to a unique column

so this is my table
CREATE TABLE "client" (
"id" INTEGER,
"name" TEXT COLLATE NOCASE,
"surname" TEXT COLLATE NOCASE,
"number" TEXT UNIQUE COLLATE NOCASE,
"car_brand" TEXT,
"modele" TEXT,
"phone_nbr" TEXT,
PRIMARY KEY("id" AUTOINCREMENT));
when im adding a new statment from my java application i can add only one time NULL to the column number but i can add many nulls from the db browser
this is the code that i use
String number = tf_number.getText();
if(tf_number.getText().trim().isEmpty())
number = null;
String name = tf_name.getText();
String surname = tf_surname.getText();
String phoneNbr = tf_phoneNbr.getText();
String car_brand = tf_brand.getText();
String modele = tf_modele.getText();
Client c = new Client(name, surname, number, car_brand, modele, phoneNbr);
ClientCRUD pcd = new ClientCRUD();
pcd.addClient(p);
and this is the sql error
[SQLITE_CONSTRAINT_UNIQUE] A UNIQUE constraint failed (UNIQUE constraint failed: client.number)
this is the addClient() fonction
public void addClient(Client t) {
try {
String requete = "INSERT INTO CLIENT(name,surname,number,car_brand,MODELE,phone_nbr)"
+ "VALUES ('"+t.getClientName()+"','"+t.getClientSurname()+"','"+t.getNumber()+"',"
+ "'"+t.getCarBrand()+"','"+t.getModele()+"','"+t.getPhone()+"')";
Statement st = MyConnection.getInstance().getCnx()
.createStatement();
st.executeUpdate(requete);
System.out.println("Client added");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
any solution ?
public void save(Person person) {
String query = "INSERT INTO person_info (" +
" name_p, " +
" age, " +
" address, " +
" email " +
")" +
"VALUES(?, ?, ?, ?)";
try(Connection connection = dbConnection.getConnection()) {
PreparedStatement prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, person.getName());
prepStatement.setInt(2, person.getAge());
prepStatement.setString(3, person.getAddress());
prepStatement.setString(4, null);
prepStatement.execute();
}
catch (SQLException e){
e.printStackTrace();
}
}
##This will solve your problem
You code inserts the string "null" and not a real null like your browser do.
So there can be only 1 string with value "null" in that unique column.
You can use preparedStatement with parameters instead of the statement you use.
E.g:
PreparedStatement preparedStatement = connection.prepareStatement(sql))
This answers how to insert null using prepared statement: Insert null using prepared statement
And your sql string for the query should have the parameters.
See more about prepared statements: Prepared Statements Tutorial

SQL-Java: Prepared Statement gives Index out of range Error

I have the following code:
try {
userPasswordNew = new String(ChangePW.passwordFieldconfirm.getPassword());
PreparedStatement prepStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET password = " + userPasswordNew + " WHERE username = " + username);
prepStmt.setString(2, BCrypt.hashpw(userPasswordNew, BCrypt.gensalt(bcryptRounds))); //2 represents number of column in database starting with 0
System.out.println(prepStmt);
return prepStmt.executeUpdate() != 0;
} catch (SQLException e) {
e.printStackTrace();
}
I tried 1 2 and 3 as indexes but everytime it throws an Index out of range exception. Is there another way to get the column, maybe adressed with its name? Or what am I doing wrong?
Could somebody please help?
To use prepared statements - please use ? instead provided values. Like in this sample:
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
To get more, please look here. In your case that could be:
PreparedStatement prepStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?");
prepStmt.setString(1, "that new password");
prepStmt.setString(2, "user_name");
I assume password and username are textual values. Hence you will have to enclose the values by quotes.
That is the query will be
"UPDATE " + TABLE_NAME + " SET password = " + userPasswordNew + " WHERE username = " + username
Also, as you are using PreparedStatement, you must not mention the variables in the query. A neater approach would be to use ? instead. Something like this.
"UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?
And then use .setString() etc methods with userPasswordNew and username.
Check this, https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
When you use PreparedStatement, you define the parameters to pass in the sql statement by placing 1 or more ?.
Then you pass values to these parameters with methods like setString(), setInt(),... The order of the parameters is not 0 based but 1 based.
try {
userPasswordNew = new String(ChangePW.passwordFieldconfirm.getPassword());
PreparedStatement prepStmt =
connection.prepareStatement("UPDATE " + TABLE_NAME +" SET password = ? WHERE username = ?");
prepStmt.setString(1, userPasswordNew);
prepStmt.setString(2, username);
System.out.println(prepStmt);
return prepStmt.executeUpdate() != 0;
} catch (SQLException e) {
e.printStackTrace();
}
In your code there is this line:
prepStmt.setString(2, BCrypt.hashpw(userPasswordNew, BCrypt.gensalt(bcryptRounds)));
I don't know if this is a parameter that you want to pass.
If it is I can't see a ? placeholder in the sql statement.

Getting "Query does not returns results" SQL exception

I was trying to make a register program in Java in Eclipse.
But i got an error :
java.sql.SQLException: Query does not return results
You can see my following code :
Login.addnewuser(lblname.getText(), lblusername.getText(), lblpseudo.getText(), passwordField.getText(), rankchoice.getSelectedItem());
of :
public static void addnewuser(String Name, String Username, String Pseudo, String Password, String Rank) {
String query = ("INSERT INTO UsersInfos (Name, Username, Pseudo, Password, Rank) " + "VALUES ('" + Name + "' , '" + Username + "' , '" + Pseudo + "' , '" + Password + "' , '" + Rank + "')");
connection = SqliteConnection.dbConnector();
try {
PreparedStatement name2 = connection.prepareStatement(query);
name2.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
Can someone help me please ? Thanks :) !
For INSERT, UPDATE or DELETE use the executeUpdate() method and for SELECT use the executeQuery() method which returns the ResultSet.

JavaFX update a Sqlite table

I am currently working on a program the function of which is to store my passwords, and this is why I am using an SQL database called Users. This database contains tables for all the users which will be using the program. Those tables have four columns:
SiteName, Username, Password, AdditionalInfo
I am having a problem updating a specific row. This is my the code I get an error with:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
stmt = c.createStatement();
String update = "UPDATE " + user + " set Username = " + usernamej + " where SiteName = " + siteEdited;
stmt.executeUpdate(update);
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
It is in a class made specifically for dealing with the sql database and it gets the following error when I try to change the username to 'test':
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such column: test)
Assuming the value you pass in for user is the name of the table, your update string is going to look like
UPDATE usertable SET Username = test where SiteName = siteEditedValue
You need to quote the string values:
UPDATE usertable SET Username = 'test' where SiteName = 'siteEditedValue'
The quick and dirty way is:
String update = "UPDATE " + user + " set Username = '" + usernamej + "' where SiteName = '" + siteEdited + "'";
However, it's much (much, much) better to use a PreparedStatement in this case:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
This code assumes the type of stmt is PreparedStatement, not just Statement.
As well as taking care of quoting the values for you, this will escape any sql for you, preventing the possibility of SQL-injection attacks (while these are far less of an issue in a desktop application that a web application, it's still a good habit to get into).
#griFlo I got it running with this code:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
PreparedStatement stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate(update);
c.commit();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
I had forgotten to put c.commit();

Categories

Resources