Java MySQL UPDATE error using WHERE in conjunction with AND - java

I am trying to UPDATE an entry in MySQL, the structure of the table is table_rankings (ip text, field text, rank double). Where ip is a user's IP address, field is an object being ranked and rank is the numerical rank of a field. My statement is:
//String for query
String query = "UPDATE "+catagory+"_rankings SET rank = ? WHERE ip = ? AND field = ? )";
PreparedStatement ps = conn.prepareStatement(query);
//fill ? variables
ps.setDouble(1, r[i]);
ps.setString(2, user);
ps.setString(3, s[i]);
ps.executeUpdate();
In this code catagory refers to a given table, for instance baseball_rankings or basketball_rankings. The error I am receiving is:
SQLException: 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 ')' at line 1
SQLState: 42000
VendorError: 1064
Is the issue that I cannot use WHERE as well as AND in an UPDATE statement? I am also curious if my update is subject to a SQL injection attack because I am using catagory+"_rankings". I have tried to use a ? variable however it results in another error.

you add a extra “)”, or can say, you missed a "(".
try
String query = "UPDATE "+catagory+"_rankings SET rank = ? WHERE ip = ? AND field = ? ";

Related

How to convert " ' " to " ` " in java

The syntax that from the java code is not applicable to mysql. The setString() from java will come out with ' and not ` which is not accepted in mysql.
I tried in my localhost to run the code, it really not accepting 'doctor' and only accept ``doctor`.
Below are my code:
PreparedStatement ps = con.prepareStatement("SELECT id FROM ? WHERE id = ?");
ps.setString(1, "doctor");
ps.setInt(2, 123);
ResultSet rs = ps.executeQuery();
and there is an error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 ''doctor' WHERE id = 123' at line 1
It's because your code produces following query:
SELECT id FROM 'doctor' WHERE id = 123
As you can see table name is used as a String which is invalid SQL Syntax, so you can either hard code table name and or if you really want it to be dynamic you can achieve it like:
String sql = String.format("SELECT id from %s where id = ?", tblName);
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 123);
ResultSet rs = ps.executeQuery();

getting the result of sql command in java [duplicate]

This question already has an answer here:
java.sql.sqlexception column not found
(1 answer)
Closed 4 years ago.
i need to get the last id entered in my data base witch is AUTO_INCREMENT so i did this
String Var = "SELECT MAX(id) FROM goupe ; ";
ResultSet vari=st.executeQuery(Var);
while(vari.next()){
nombre = vari.getInt("id");}
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)VALUES('"+name+"','"+familly+"','"+email+"','"+pass+"','"+module+"','"+specialite+"','"+card+"','"+nombre+"');";
st.execute(sql);
but i had this problem Column 'id' not found.
so what should i do to have it right .
I have to say, there are a couple of really easy things you can do to greatly improve your code.
If your latest ID is generated elsewhere, then embed the query directly into the statement such that you don't need to go get it. That will reduce the risk of a race condition.
Use PreparedStatements. Let me ask you this question: What do you suppose is going to happen if one of your user's name is O'Ryan?
Since your code is just a snip, I also will only provide a snip:
int index = 1;
String sql = "INSERT INTO Student(name,famillyname,email,password,module,speciality,card,id_goupe)" +
"VALUES(?,?,?,?,?,?,?,(SELECT MAX(id) FROM goupe));";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(index++, name);
ps.setString(index++, familyname);
ps.setString(index++, email);
ps.setString(index++, password);
ps.setString(index++, module);
ps.setString(index++, speciality);
ps.setString(index++, card);
int rows = ps.executeUpdate();
if(rows == 1) {
System.out.println("Successfully inserted row");
}
When you execute the query SELECT MAX(id) FROM goupe;, then in the returned table, the column name no longer remains as id.
So, the best approach is to provide a name for the column like below:
SELECT MAX(id) AS maxid FROM goupe;
Then, you can get the value using:
vari.getInt("maxid")

SQLServer Exception: Invalid column name

com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'IDPaciente'
I am getting this exception. This is my code:
String query = "INSERT INTO Paciente('IDPaciente', 'NomePaciente', 'IdadePaciente', 'LocalidadePaciente') VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')";
try
{
st = con.DatabaseConnection().createStatement();
rs = st.executeQuery(query);
}
I suspect the problem might be in the query itself.
I have searched a lot and couldn't find the solution to my problem. I have tried refreshing the cache, changing permissions within the schema, restarting sql server (I am using sql server management studio 2012), I am correctly connected to my database, and nothing seems to work.
What could I be doing wrong?
Thank you!
Remove quotes , try :
String query = "INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente) VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')";
try
{
st = con.DatabaseConnection().createStatement();
rs = st.executeQuery(query);
}
Remove also quotes for INT values.
Your code is not secure, you can easily get Syntax error or SQL Injection I suggest to use PreparedStatement instead.
You have a problem in your Query, the columns should not be between '' so you can use this instead :
String query = "INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, "
+ "LocalidadePaciente) VALUES(?, ?, ?, ?)";
try (PreparedStatement insert = con.prepareStatement(query)) {
insert.setString(1, IDTextField.getText());
insert.setString(2, NomeTextField.getText());
insert.setString(3, IdadeTextField.getText());
insert.setString(4, LocalidadeTextField.getText());
insert.executeUpdate();
}
If one of your column is an int you have to use setInt, if date setDate, and so on.
You have four problems, though only the first is giving you the current error:
Single-quotes (') are for quoting text literals, not column names. In MS SQL Server, you can quote column names using double-quotes (") or square brackets ([]), but you don't need to quote them at all.
To prevent SQL Injection attacks, where hackers will steal your data and delete your tables, and to prevent potential syntax errors, never build a SQL statement with user-entered strings, using string concatenation. Always use a PreparedStatement.
Always clean up your resources, preferably using try-with-resources.
Don't use executeQuery() for an INSERT statement. Use executeUpdate(). As the javadoc says:
Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
So, your code should be:
String query = "INSERT INTO Paciente" +
" (IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente)" +
" VALUES (?, ?, ?, ?)";
try (PreparedStatement st = con.DatabaseConnection().prepareStatement(query)) {
st.setString(1, IDTextField.getText());
st.setString(2, NomeTextField.getText());
st.setString(3, IdadeTextField.getText());
st.setString(4, LocalidadeTextField.getText());
st.executeUpdate();
}
Remove the quotes from your column names.
"INSERT INTO Paciente(IDPaciente, NomePaciente, IdadePaciente, LocalidadePaciente) VALUES('"+IDTextField.getText()+"', '"+NomeTextField.getText()+"', '"+IdadeTextField.getText()+"', '"+LocalidadeTextField.getText()+"')"
The Column names are does not typed within quotes, Remove them and try again.
Demo:-
Create table MyTable (id int , name varchar (50))
go
insert into MyTable (id,name) values (1 , 'ahmed')
Result:-
(1 row(s) affected)
Try insert them again with quotes.
insert into MyTable ('id','name') values (1 , 'ahmed')
Result:-
Msg 207, Level 16, State 1, Line 3
Invalid column name 'id'.
Msg 207, Level 16, State 1, Line 3
Invalid column name 'name'.

How do i correctly enter a Decimal Type through JDBC?

I've connected a java project (using netbeans) to a MySQL database, but I'm having trouble inserting data.
If i use this code it inserts just fine:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('milk', 3.18, '2015-01-23','Grocery');";
but when i try and replace the insert values with these predefined values:
String ExpenseName;
Double ExpenseCost;
String ExpenseDate;
String ExpenseType;
and then use this code to insert the values:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('"+ExpenseName+"',"+ExpenseCost+",'"+ExpenseDate+"','"+ExpenseType+"');";
I get the error: SQLException: Column 'Cost' cannot be null
my cost field in my database is defined as decimal(15,2)
Even more annoyingly, when i try and use this code to update as a test:
String update = "insert into expenses(Expense,Cost,Purchase_Date,Description)\n" +
"values('"+ExpenseName+"',3.18,'"+ExpenseDate+"','"+ExpenseType+"');";
i get another error saying:
SQLException: Data truncation: Incorrect date value: 'null' for column 'Purchase_Date' at row 1
this is confuses me a lot because through the database i have no issues with updating the Purchase_Date field in the expenses table with a '2015-01-23'. if its of any use that field is of type date. perhaps it's because the date object in my java is string?
You really should use a PreparedStatement
PreparedStatement pst= con.prepareStatement(
"insert into expenses(Expense,Cost,Purchase_Date,Description)" +
" values(?, ?, ?,?)");
pst.setString(1, ExpenseName);
pst.setDouble(2, ExpenseCost);
pst.setDate(3, new java.sql.Date(ExpenseDate.getTime()));
pst.setString(4, ExpenseType);
pst.executeUpdate();
Also, you should inititalize your variables properly.
Assuming that they are declared as fields, you should initialize them as :
String ExpenseName="SomeName";
Double ExpenseCost=1.8;
Date ExpenseDate=new Date();
String ExpenseType="Some Type";
Uninitialized variables could be the source of the SQLException, because ExpenseName and ExpenseDate would be concatenated as "null" in your SQL string.
You should always use a PreparedStatement to insert/ update data and not use String concatenation. This will not only help you with formatting the data correctly but also protect you against SQL injection attacks.

MySQL syntax error using Java in Eclipse

I have the following prepared statement for sql in Java :
com.mysql.jdbc.JDBC4PreparedStatement#6e56103e:
INSERT INTO `game` (Id , GameStart ,Name, Lenght, MapVersion, Mode)VALUES(2502591,'2000-03-02 02:02:02','5x5 aptb wdw','00:55:48','DotA v6.75b.w3x','aptb ')ON DUPLICATE KEY UPDATE `Id`=VALUES(Id),`GameStart` = VALUES(GameStart),`Name`=VALUES(Name),`Lenght`=VALUES(Lenght),`MapVersion`=VALUES(MapVersion),`Mode`=VALUES(Mode).
When I execute it in Eclipse I get the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '?,?,?,?,?,?)ON DUPLICATE KEY UPDATE `Id`=VALUES(Id),`GameStart` = VALUES(GameSta' at line 1.
But at the same time when I execute the same query in SQLyog I don't get an error. Rows are updated. What can be a problem? Thanks in advance
Code:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dota","root","root");
PreparedStatement updateGame = null;
String updatingGame = "INSERT INTO `game` (Id , GameStart ,Name, Lenght, MapVersion, Mode)" +
"VALUES(?,?,?,?,?,?)" +
"ON DUPLICATE KEY UPDATE " +
"`Id`=VALUES(Id),"+
"`GameStart` = VALUES(GameStart)," +
"`Name`=VALUES(Name)," +
"`Lenght`=VALUES(Lenght)," +
"`MapVersion`=VALUES(MapVersion)," +
"`Mode`=VALUES(Mode)";
con.setAutoCommit(false);
updateGame=con.prepareStatement(updatingGame);
updateGame.setInt(1, game.Id);
Timestamp timestamp = new Timestamp(100,2,2,2,2,2,2);
updateGame.setTimestamp(2,timestamp);
updateGame.setString(3, game.GameName);
updateGame.setTime(4, (Time) game.Time);
updateGame.setString(5, game.MapVersion);
updateGame.setString(6, game.Mode);
updateGame.executeUpdate(updatingGame);
And on:
updateGame.executeUpdate(updatingGame);
I get an error
Firstly if you are using a preparedStatement you have to do it this way
String query="Insert into tablename (col1, col2) values(?,?)";
PreparedStatement stmnt = //get the statement
stmnt.setString(1, "col1val");
stmnt.setString(2, "col2val");
You are inserting a duplicate value on the primary key.
Follow the #chaitanya10 suggestion, use PreparedStatement
How is your knowledge about Object Orientation? As I can see you aren't using correctly encapsulation.
Found my mistake. I should use only executeUpdate() instead of executeUpdate(updatingGame) ;, because if I use it with parameter, I will overwrite values whiten by
updateGame.setInt(1, game.Id);
Timestamp timestamp = new Timestamp(100,2,2,2,2,2,2);
updateGame.setTimestamp(2,timestamp);
updateGame.setString(3, game.GameName);
updateGame.setTime(4, (Time) game.Time);
updateGame.setString(5, game.MapVersion);
updateGame.setString(6, game.Mode);

Categories

Resources