Prepared statement update issue - java

I've started using prepared statement for my sql updates, but I seem to be getting a snag when I'm updating. The logic seems sound but I get an error whenever it goes into the update segment. I can delete or insert fine. Anywho...
Connection con = getDBConnection();
PreparedStatement pstmt = null;
String query = "update table set int = ?, String= ? where int= ? and date= ?";
pstmt = con.prepareStatement(query);
pstmt.setInt(1, var);
pstmt.setDate(2, sqlDate);
pstmt.setInt(3, intVar);
pstmt.setString(4, stringVar);
pstmt.executeUpdate();
Am I doing something wrong here? I've done all the troubleshooting I can and everything seems fine except for this, potentially.
Error = "A non-numeric character was found where a numeric was expected"

You've got your string and date the wrong way round - you're calling setDate(2, ...) when the second parameter is in the context of "String = ?" and setString(4, ...) when the fourth parameter is in the context of "date = ?".
Admittedly the error you're getting is somewhat odd for that, but it's all I can see...

Related

Working on this Java project where I need to be able to delete data from the database on user's request

The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: 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 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);

Dynamic variable in executeUpdate (Java)

I have the following connection, statement and executeUpdate
Connection con = DBConnPool.getInstance().getConnection();
Statement stmt = con.createStatement();
//String str1 = "update node set compareflag=0, personalid=NULL where ipaddress='192.168.150.213'";
String str1 = "update node set compareflag=0, personalid=NULL where ipaddress='var3.getIpAddress()'";
stmt.executeUpdate(str1);
The commented out String line works perfectly, the other one ignores the value returned by var3.getIpAddress() even though that variable does contain the correct data which I use in other areas of my code.
Do I have to create a separate variable first and then equate it to var3.getIpAddress() ?
Any thoughts appreciated, it's probably insufficient " or " in the wrong place.
Prefer a PreparedStatement with a bind parameter. Dynamically building a query leaves you vulnerable to SQL Injection attacks. PreparedStatement (when used correctly) is immune to SQL Injection. It also makes the code easier to read and reason about. For example,
Connection con = DBConnPool.getInstance().getConnection();
String qry = "update node set compareflag=0, personalid=NULL where ipaddress=?";
PreparedStatement stmt = con.prepareStatement(qry);
stmt.setString(1, var3.getIpAddress());
stmt.executeUpdate();
You should use PreparedStatement to set parameter for safe.
PreparedStatement pstmt = con.prepareStatement("update node set compareflag=0, personalid=NULL where ipaddress=?");
pstmt.setString(1,var3.getIpAddress());
pstmt.executeUpdate();

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'.

Unknown column error in where clause, using MySQL and Java

Following is my code line :
ResultSet rs3 = stmt6.executeQuery("SELECT * FROM ShopSystem.Order where s_id="+s_id+" AND status="+Pending);
I am getting the following error :
Unknown column 'Pending' in 'where clause'
What could be the reason... I cant get through it..
No doubt, status is a string, so it needs to be compared to a string. Use delimiters:
SELECT * FROM ShopSystem.Order where s_id="+s_id+" AND status='"+Pending+"'"
Or better yet, learn how to write code that uses parameter substitution for putting parameter values into SQL strings.
Change it to
AND status = '" + Pending + "'"
You need to put the string in quotes. Otherwise the DB thinks you mean a column name.
But actually you should use Prepared Statements. Then you don't need to patch the queries together like this and you don't worry about parameters and escaping them...
Don't make concatenation ! Use prepared statements
PreparedStatement stm = conn.prepareStatement("SELECT * FROM ShopSystem.Order where s_id = ? AND status = ?");
stm.setInt(1, s_id);
stm.setString(2, Pending.name());
ResultSet rs = stm.executeQuery();
you must use the PreparedStatement in this case
// use the ? for the 2 entries values
String selectSQL = new String("SELECT * FROM ShopSystem.Order where s_id=? AND status=?")
preparedStatement = dbConnection.prepareStatement(selectSQL);
// in order you must incialise them here
preparedStatement.setString(1, "s_id");
preparedStatement.setString(2, "Pending");
//execute your resultset `enter code here`
ResultSet rs = preparedStatement.executeQuery();

Java preparestatement request doesn't work

I have a java code, where i'm doing a SQL request by using prepareStatement
String requete = "select * from VOreservation"
+ " where id_enseignant = ? and date_reservation = ? and id_creneau = ? ";
PreparedStatement pstmt = con.prepareStatement(requete);
pstmt.setInt(1, ens.getIdEnseignant());
pstmt.setDate(2, date);
pstmt.setInt(3, creneau.getIdCreneau());
ResultSet rset = pstmt.executeQuery();
I have a java.sql.sqlException, so It should be a problem with my request, but for me it is fine
The first and last parameters are number in my DB, and the second is a date (and date is here a java.sql.date)
I'm using the driver: oracle.jdbc.driver.OracleDriver
my error is:
Fail to construct descriptor: Unable to resolve type: (my nested table type)
The problem could be with the JDBC driver for the DBMS you are using. Not all drivers implement the standard completely and correctly. There is not enough information in your question to tell what goes wrong.

Categories

Resources