Using MySQL by Java - java

I'm coding some database transactions by using java. I'm sending a query using java. I think it has no problem with it. And if I send the query at prompt, it is working.
This method is updating book quantity.
private static void updateBquantity(int bqt, String bname) {
Connection con = makeConnection();
try {
Statement stmt = con.createStatement();
System.out.println(bqt + " " +bname);
//this part is making problem
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where bookname = '" + bname + "';");
System.out.println("<book quantity updated>");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where 도서이름 = '" + bname + "';");
This part is making problem.
Other queries using this form is working.
The compiler says :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'bookname = 'Davinci Code'' at line 1
Help me.

I'm confused with bookname = 'Davinci Code, where is bookname in your query? No matter what, in this query, you missed a blank before where, try this:
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + " where 도서이름 = '" + bname + "';");

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.

How to update a row of entries in a database (JavaDatabase) that is connected to my JTable?

I am making a program without knowing much about programming... I used some youtube videos to help me.
My program is made for a chef that can edit users & food and gather ratings and suggestions from the inspector. The chef's section of editing users' details works.
However, the inspector's rating does not as it throws an error: SQLSyntaxException: Encountered "Vegetarian" at line 1, column 65. I believe it is because of getting the rating value (which is int) in a wrong way...
'
public void getConnection(){
try{
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1327/MyApp", "Me", "Me");
mystatObj=myconObj.createStatement();
myresObj=mystatObj.executeQuery("Select * from Me.Food");
tableRateFood.setModel(DbUtils.resultSetToTableModel(myresObj));
}
catch (SQLException e){
e.printStackTrace();
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "update Me.Food set Name = '" + nameText.getText()
+ "',Type = '" + typeText.getText()
+ "', Rating = '" + ratingText.getText()
+ ", 'Vegetarian = '" + vegetarianText.getText()
+ "', ShownOnMenu = '" + showText.getText()
+ "' where Id = " + idText.getText();
//tried the following... did not work either
/*+ " Rating = " + Integer.parseInt(ratingText.getText()));*/
Statement update= myconObj.createStatement();
update.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Updated successfully!");
}
catch(SQLException E){
E.printStackTrace();
}
getConnection();
}
Your forgot a quote in ", 'Vegetarian = '"
Talking about building query strings, you should avoid +-ing values and rely on prepared statements with sql parameters instead. Allows the database to cache the query and avoids sql injection attacks. And spares you formatting headache, think about date values.

SQL database update statement not working

ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;

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();

Update Statement - Syntax error in UPDATE statement (Java & MS Access)

I am trying to update a MS Access database. I have searched this and I have tried everything I have found but I am still getting the following error.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
Any help would be very helpful. My code is below...;
String sqlStatement = "UPDATE ProductCatalogue"
+ "SET [StockLevel] = ?"
+ "WHERE [ProductID] = ?;";
PreparedStatement prepStatement = connection.prepareStatement(sqlStatement);
prepStatement.setInt(1, quantity);
prepStatement.setInt(2, productID);
//= "UPDATE ProductCatalogue"
//+ "SET StockLevel = " + quantity
//+ "WHERE ProductID = " + productID + ";";
try {
//myStatement.executeUpdate(sqlStatement);
prepStatement.executeUpdate();
} catch (SQLException sqle) {
System.out.println("Oopss...." + sqle);
}
connection.close();
prepStatement.close();
you may need a few whitespaces. Try:
String sqlStatement = "UPDATE ProductCatalogue "
+ "SET [StockLevel] = ? "
+ "WHERE [ProductID] = ?;";
(note the space after ProductCatalogue and the first ?)

Categories

Resources