I'm trying to update a table from a Java application where a certain column may be NULL. I have tried several different approaches but I always get the following error:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: 'null' for column 'scheidingsdatum' at row 1
I made sure that the table allowed NULL values for the scheidingsdatum field, and can insert NULL values when directly inserting in MySQL
This is the table structure in PHPMyAdmin:
The tables use innoDB
I have tried the following solutions:
1: Just use the NULL variable in a parameter
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = ? "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setString(4, scheidingsdatum);
stmnt.setString(5, nummer);
2: Hardcode NULL in the query (inside if/else block)
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = NULL "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setString(4, nummer);
3: Use setNull(4, java.sql.Types.DATE)
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = ? "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setNull(4, java.sql.Types.DATE);
stmnt.setString(5, nummer);
4: Use setNull(4, java.sql.Types.NULL)
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = ? "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setNull(4, java.sql.Types.NULL);
stmnt.setString(5, nummer);
the following is my database.properties file and connection creation:
database.properties
jdbc.drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://IP:3306/TABLE_NAME
jdbc.username=USER
jdbc.password=PASSWORD
Connection creation
Class.forName(props.getProperty("jdbc.drivers")).newInstance();
this.conn = (Connection) DriverManager.getConnection(props.getProperty("jdbc.url"),props.getProperty("jdbc.username"),props.getProperty("jdbc.password"));
I just made a test and it worked for me with stmnt.setNull(4, java.sql.Types.Date);, are you sure that for stmnt.setString(3, huwelijksdatum); the value of huwelijksdatum is a valid mysql date string and not "null" ?
Well, this is the dumbest fix ever.
The code was originally made by someone else, and I only expanded on it a bit. They first created a string scheidingsDatum = "null";, which would then be overwritten by an actual date if there was one.
I assumed (I know, it's never smart to assume) that it would be null (Notice the lack of quotation marks?) when it didn't have a value.
So, in my check, the string wasn't null (since it was "null") and so the first part was executed. Which made it try to insert a string "null", which is obviously an incorrect date.
Simply modifying the string to be null instead of "null" upon instantiation fixed the issue.
You could try TIMESTAMP instead of DATE in your prepared statement.
stmnt.setNull(4, java.sql.Types.TIMESTAMP);
If scheidingsdatum is a nullable field, then simply remove it from your UPDATE statement when its value is null. In other words, when scheidingsdatum is null, change the statement to:
UPDATE gezinnen SET ouder1 = ?, ouder2 = ?, huwelijksdatum = ?
WHERE gezinsNummer = ?
Related
I am struggling with checking if a table exist in the DB. What I have done so far is as follows:
public boolean isTableExist(String tableName) {
JdbcTemplate jdbc = getJdbcTemplate();
String query =
"IF (OBJECT_ID(?) IS NOT NULL ) "
+ "BEGIN "
+ " PRINT 1 "
+ " RETURN "
+ "END "
+ "ELSE "
+ "BEGIN "
+ " PRINT 0 "
+ " RETURN "
+ "END";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
return result == 1 ? true : false;
}
Output (Error):
PreparedStatementCallback; uncategorized SQLException for SQL [IF
(OBJECT_ID(?) IS NOT NULL ) BEGIN PRINT 1 RETURN END ELSE BEGIN
PRINT 0 RETURN END]; SQL state [null]; error code [0]; The statement
did not return a result set.; nested exception is
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not
return a result set.
You can also run a query like so:
select count(*)
from information_schema.tables
where table_name = 'yourtablename'
-- optionally this too
-- and table_schema = 'dbo';
If you get zero, table doesn't exist.
Based on jdbctemplate count queryForInt and pass multiple parameters answer, it seems like you might have to use something like this once you store the query
jdbc.queryForObject(
"select count(*) from information_schema.tables where table_name = ?"
, new Object[] { tableName }
, Integer.class
);
Update:
The problem has been resolved with the help of this post and the final solution based on the above info is:
String query =
"select count(*) "
+ "from information_schema.tables "
+ "where table_name = ? and table_schema = 'dbo'";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
I am trying to change a normal query to Parameterized query using jdbcTemplate.queryForObject for avoiding SQL Injection. But the query returns EmptyResultDataAccessException - Incorrect result size: expected 1, actual 0 where the normal query works fine. Below is the normal query where i get the correct result.
StringBuilder builder = new StringBuilder();
String AcctNameBuilder = adhpDetailUtil.getAccName();
builder.append("select * " +
"from gfc.LSI_ELGBLTY " +
"where INSURANCE_ID = '" + request.getInsuranceId() + "' and " +
"SYS_CD = '" + request.getSystemId() + "' and " +
"ACCT_TYPE in (" + AcctNameBuilder.toString() + ")");
Here is the parameterized query that i have created from the above query.
StringBuilder builder = new StringBuilder();
String AcctNameBuilder = adhpDetailUtil.getAccName();
final String QUERY = "select * " + "from gfc.LSI_ELGBLTY " + "where INSURANCE_ID = ? and " + "SYS_CD = ? and " + "ACCT_TYPE in (?)";
Object[] params = new Object[] {
request.getInsuranceId(),request.getSystemId(),AcctNameBuilder};
String ids = jdbcTemplate.queryForObject(QUERY, params, String.class);
builder.append(ids)
In the first case, builder.append contains the exact query while in the second case jdbcTemplate.queryForObject is returning EmptyResultDataAccessException. What am I doing wrong here.
I don't believe you can just append ids for an "IN" clause like that.
The parameter for the "IN" clause is technically an Array. I ran into this a number of years ago and I don't think that this has ever been truly addressed.
If you think about it this is a fairly difficult problem as the query planner for preparing the statement cannot effectively bound the number of parameters.
I have looked through similar threads on this site and none of the suggested answers seem to work. I am writing a java program that interacts with an Access database using SQL. I have successfully connected to the database and pulled information from it. However, I need to update the database and I keep running into this error
UCAExc:::3.0.7 user lacks privilege or object not found: SLIPSET
Why am I not able to successfully update the Access database?
Here is the code relevant to the updates
String sqlSlip ="UPDATE Slip" +
"SET slipOpen = 0 AND boatID =?" +
"WHERE slipNumber = ?";
PreparedStatement slipUpdate = connection.prepareStatement(sqlSlip);
slipUpdate.setDouble(1, boatIDdub);
slipUpdate.setDouble(2, rs.getInt("slipNumber"));
ResultSet updateSlip = slipUpdate.executeQuery();
String sqlCustomer = " INSERT INTO Customer(customerLName, customerFName, slipNumber, boatID, customerNumber)" +
"VALUES (?, ?, ?, ?, ?)";
PreparedStatement custUpdate = connection.prepareStatement(sqlCustomer);
custUpdate.setString(1,custLName);
custUpdate.setString(2, custFName);
custUpdate.setDouble(3, rs.getInt("slipNumber"));
custUpdate.setDouble(4, boatIDdub);
custUpdate.setDouble(5, customerNumber);
ResultSet updateCust = custUpdate.executeQuery();
connection.close()
If you were to inspect the contents of your sqlSlip string you would see that it contains
UPDATE SlipSET slipOpen = 0 AND boatID =?WHERE slipNumber = ?
You need to add a space to the end of each string fragment and use a comma instead of AND ...
String sqlSlip ="UPDATE Slip " +
"SET slipOpen = 0, boatID = ? " +
"WHERE slipNumber = ?";
... so that the string contains
UPDATE Slip SET slipOpen = 0, boatID = ? WHERE slipNumber = ?
Also note that to perform an INSERT query you need to use .executeUpdate(), not .executeQuery().
I have a table in H2 DB
Order
--------
id (key)
MarketId1
MarketId2
MarketId3
ListName1
ListName2
ListName3
From XML I'm getting list of ListOrder
public final class ListOrder
{
public long listId;
public String Name;
}
So I have 3 prepared statements
"UPDATE Order set " + ListName1 + " = ? WHERE " + MarketId1 + " = ?"
"UPDATE Order set " + ListName2 + " = ? WHERE " + MarketId2 + " = ?"
"UPDATE Order set " + ListName3 + " = ? WHERE " + MarketId3 + " = ?"
The in a method I prepare a list of PreparedStament to execute
final PreparedStatement statement1 = connection.prepareStatement(QUERY1);
final PreparedStatement statement2 = connection.prepareStatement(QUERY2);
final PreparedStatement statement3 = connection.prepareStatement(QUERY3);
for (ListOrder listOrder: listOrders)
{
statement1.setString(1, listOrder.Name);
statement1.setLong(2, listOrder.listId);
statement1.addBatch();
statement2.setString(1, listOrder.Name);
statement2.setLong(2, listName.listId);
statement2.addBatch();
statement3.setString(1, listName.Name);
statement3.setLong(2, listOrder.listId);
statement3.addBatch();
}
return new ArrayList<PreparedStatement>(){{add(statement1); add(statement2); add(statement3);}};
I'm a SQL noob. Is there any better way of doing it? I assume that MarketId 1 2 3 could be the same. ListNames could be null (there will be at least one)
UPDATE:
In code I would write something like this (prob change to HashMap)
for (ListOrder listOrder: listOrders)
{
for(Order order : orders)
{
if(order.marketID1 == listOrder.listID)
order.listName1 = listOrder.Name; //break if no dups
if(order.marketID2 == listOrder.listID)
order.listName2 = listOrder.Name;
if(order.marketID3 == listOrder.listID)
order.listName3 = listOrder.Name;
}
}
You can use update comma separated
UPDATE <TABLE>
SET COL1 = <VAL1>,
COL2= <VAL2>
WHERE <CONDITION>
Is it this what you expect as one update query?
Unless you are trying to update the same record, then there is no way to do this easily or efficiently in a single query. Otherwise, assuming this is the desired result, you could use an OR (or an AND if that is desired) statement such as:
UPDATE Order
SET ListName1=?, ListName2=?, ListName3=?
WHERE MarketId1=? OR MarketId2=? OR MarketId3=?
You might also consider updating your table to use a one:many relationship which might make your queries easier. For example:
Order
--------
id (key)
name
etc
Market_List
--------
id (key)
order_id (fk)
market
listname
I try to create a PreparedStatement:
stmt = conn.prepareStatement("SELECT POLBRP, POLTYP, POLNOP, INCPTP, TRMTHP, " +
"CLTKYP , CANDTP, POLSTP, EXPRYP, OINCPP, CANRNP, PAYMDP,
KCNFLP, KCRTSP, KACADP, KSCHMP, EXPRYP FROM "
+ POLHDR + " WHERE POLNOP = " + idNumber +
" AND POLBRP = " + branch + " AND POLTYP = " + product +
" AND OINCPP <= "+date );
And this throws an SQLException: [SQL0206] Column AD not in specified tables.
I have no idea where it's getting column AD from as I never specified it in the select clause (unless I'm being completely blind and stupid)
Can anyone help?
If your variables are strings, e.g. branch
" AND POLBRP = " + branch + " ...
then you forgot to quote the values
" AND POLBRP = '" + branch + "' ...
but the real solution is using placeholders
... AND POLBRP = ? ...
which would prevent such problems once and for all, this is what PreparedStatement is designed for
Try to change your query into this:
SELECT
POLBRP,
POLTYP,
POLNOP,
INCPTP,
TRMTHP,
CLTKYP,
CANDTP,
POLSTP,
EXPRYP,
OINCPP,
CANRNP,
PAYMDP,
KCNFLP,
KCRTSP,
KACADP,
KSCHMP,
EXPRYP
FROM TableName WHERE POLNOP = ? AND POLBRP = ? AND POLTYP = ? AND OINCPP <= ?";
Then use:
stmt.setString(1, "ValueOfPOLNOP");
...
When your query is being executed ? will be replaced with the value you passed into PreparedStatement#setString(int, String) method
Preventing SQL Injection in Java shows the proper use of PreparedStatement:
Prepared Statements Variables passed as arguments to prepared
statements will automatically be escaped by the JDBC driver.
Example: ps.1
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
From the same source, following in the same section:
Although Prepared Statements helps in defending against SQL Injection,
there are possibilities of SQL Injection attacks through inappropriate
usage of Prepared Statements. The example below explains such a
scenario where the input variables are passed directly into the
Prepared Statement and thereby paving way for SQL Injection attacks.
Example: ps.2
String strUserName = request.getParameter("Txt_UserName");
PreparedStatement prepStmt = con.prepareStatement("SELECT * FROM user WHERE userId = '+strUserName+'");