java.sql.PreparedStatement.setString Function getting Varchars confused with doubles - java

I have a servlet/tomcat server written in java.
I have a mysql class that I have written, and I have been using the functions in it to insert prepared statements into a mysql database using jdbc.
The function I call uses java.sql.PreparedStatement.setString in order to set the paramaters of the prepared statement. This has been working perfectly for thousands of different inputs for months on end without issue.
Recently however, when trying to use the function to insert an ip address into a VARCHAR type mysql column I am getting an exception thrown as follows:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: '10.1.1.101'
This is bizarre, There is no notion of a DOUBLE anywhere in my code, and a "Show Columns" on the mysql table ensures that the data type is in fact a VARCHAR. I have had my colleagues look at this as well to double check that I wasn't missing something simple. However we are all stumped.
My only theory is that the JDBC driver or the SetText function is taking a liberty and assuming a DOUBLE data type because the first part of the ip address is in the form of XX.XX
Any help would be great, please don't tell me to do obvious stuff like check my column data types etc. I have spent a lot of time double and tripple checking everything.

The problem is not with JDBC Driver. The problem lies with MySQL. Here is what i get on MySQL commadline:
mysql> INSERT INTO route_table (SYSTEM, IP, PORT) VALUES ("192.168.1.24:8080","192.168.1.24","8080") ON DUPLICATE KEY UPDATE IP=values(IP) AND PORT=values(PORT);
Query OK, 1 row affected (0.04 sec)
mysql> INSERT INTO route_table (SYSTEM, IP, PORT) VALUES ("192.168.1.24:8080","192.168.1.24","8080") ON DUPLICATE KEY UPDATE IP=values(IP) AND PORT=values(PORT);
ERROR 1292 (22007): Truncated incorrect DOUBLE value: '192.168.1.24'
mysql>
The problem is , the syntax of INSERT INTO .... ON DUPLICATE KEY UPDATE used by you is incorrect. You have used a keyword AND instead of using a ,(comma). So the query should be:
mysql> INSERT INTO route_table (SYSTEM, IP, PORT) VALUES ("192.168.1.24:8080","192.168.1.24","8080") ON DUPLICATE KEY UPDATE IP=values(IP), PORT=values(PORT);
Query OK, 2 rows affected (0.00 sec)

Related

INSERT INTO Statement automatically adds thousand separators to java integer starting at 1000k

I encountered a weird problem:
I have a column "MaxDealtDamage" which is for instance lower then 1000000 (1000k).
code is like this:
class xyz = PlayerData.GetData(player);
xyz.LoginTimes++;
PlayerData.SetData(xyz, player);
When it is 1000000 (1000k) or higher this error is beeing send:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.000, MaxDefense = 0 WHERE UUID='d839d1f0-ad5b-4922-841c-1d6ee05d9f56'' at line 1
Its behaving like it would try to give him a String containing "4.000.000" but its an integer with the value "4000000" (4000k). For beeing sure the output in runtime is 4000000 I doublechecked it.
Here the query:
MessageFormat.format("INSERT INTO PlayerData(UUID,VIPExpirationDate,IPv4,FirstPlayTime,LastPlayTime,TotalPlayTime,TotalLogins,MaxDealtDamage,MaxDefense) "
+ "VALUES(''{0}'',''{1}'',''{2}'',''{3}'',''{4}'',{5},{6},{7},{8});", data.UUID.toString(), DBDateFormat.format(data.VIPExpirationDate), data.IPv4, DBDateFormat.format(data.FirstPlayTime), DBDateFormat.format(data.LastPlayTime), data.TotalPlayTime, data.TotalLogins, data.MaxDealtDamage, data.MaxDefense);
MessageFormat is not a tool for creating SQL statements. It's a simple utility for building text messages with correct formatting.
You are supposed to use PreparedStatement with bind parameters as explained in the Using Prepared Statements tutorial. JDBC will take care of escaping and formatting the supplied values so they can be received by the database server while preventing SQL Injections.

Passing null Values in String Format from iBatis into an Integer value in Postgres DB

I am transferring data from 1 table (MySQL) to another (Postgres) using iBatis.
Table1(String Name, INTEGER Age, DATE dob, String Note)
The code I am using to INSERT data through Ibatis is:
<insert id="insertData" parameterType="TransferBean" >
INSERT
INTO ${base.tableName}(${base.columns})
VALUES(
${base.columnValueStr}
)
</insert>
Where columns is the list of the columns, and columnValueStr is a list of the values being passed in a comma separated format.
The base query created by iBatis being passed to Postgres is :
INSERT INTO TABLE2(Name,Age,Dob,Note) VALUES("Ayush",NULL,"Sample")
However Postgres is throwing the following error:
column \"Age\" is of type smallint but expression is of type character varying\n Hint: You will need to rewrite or cast the expression.
My guess is that Postgres is reading NULL as 'null'. I have tried passing 0 (which works), and '' (does not work) based on Column Name, but its not a generic and graceful solution.
Filtering is not possible according to the type of the column.
I need help to know if there is a workaround I can make at the query or even JAVA level which would pass the NULL as a proper null.
P.S. I have tried inserting null values into SmallInt from Postgres IDE, and that works fine.
You need to check if a variable = NULL, replace it with text NULL, as the NULL might be rendered as BLANK
make sure it is
INSERT INTO TABLE2(Name,Age,Dob,Note) VALUES('Ayush',NULL,'Sample','')
not the following: (which is not working for SQL)
INSERT INTO TABLE2(Name,Age,Dob,Note) VALUES('Ayush',,'Sample',)
Since you are transferring data from MySQL to PostgreSQL, have a try: www.topnew.net/sidu/ which might be easier for your task. Simply expert from one database, and import to another. As SIDU supports both MySQL and PostgreSQL

MySqlSyntaxErrorException wrong Query

I'm tring to create a table in mysql from java desktop program but I obtain a MySqlSyntaxErrorException.
The query is :
CREATE TABLE FileXFascia(fila0 Integer,fila1 Integer,fila2 Integer,fila3 Integer) VALUES ('3','4','3','3')
Anyone knows where I'm wrong?
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 'VALUES ('3','4','3','3')' at line 1
You need to split these as follows:
CREATE TABLE FileXFascia(fila0 Integer,fila1 Integer,fila2 Integer,fila3 Integer);
INSERT INTO FileXFascial (fila0, fila1, fila2, fila3) VALUES ('3','4','3','3');
In your question there are two different operations on a table, You are trying to create and insert data in single query even in a wrong way. First you need to create table then insert data into created table. Like below syntax.
create table tableName(col1 dataType,col2 dataType,col3 dataType,.......coln dataType);
After creation of table now you can insert data into table. Like below syntax.
insert into tableName(col1, col2,col3,......coln) values ('data1','data2','data3',......'datan');

Java MySQL PreparedStatement.setBoolean wraps value in quotes

Short version of my question is:
PreparedStatement ps;
ps = connection.prepareStatement("Insert into T values (?)");
ps.setBoolean(1, true);
ps.executeUpdate();
What can be the reasons for this code sample to produce query with value wrapped in quotes?
Long version of my question is:
I have JavaEE application with plain JDBC for DB interactions and recently I noticed that there are some MySQLDataTruncation exceptions appearing in my logs. These exceptions were occurring on attempt to save entity into DB table which have boolean column defined as BIT(1). And it was because generated query looked like this:
Insert into T values ('1');
Note that value is wrapped with quotes. Query was logged from application with Log4J log.info(ps); statement.
Previous logs demonstrate that there where no quotes.
Furthermore, even MySQL server logs started to look different. Before this happened I had given pairs of records for each query executed:
12345 Prepare Insert into T values (?)
12345 Execute Insert into T values (1)
And after:
12345 Query Insert into T values ('1')
It is worth noting that those changes wasn`t a result of deploying new version of application or even restarting MySQL/Application server and code, responsible of query generation, is as straightforward as example in this question.
Application server restart fixed the issue for about 12 hours, and then it happened again. As a temporary solution I changed BIT columns to TINYINT
P.S. Examining both aplication and MySQL logs allowed to narrow down the time span when something went wrong to about 2 minutes, but there were nothing abnormal in the logs in this period.
P.P.S. Application server is Glassfish 2.1.1, MySQL server version is 5.5.31-1~dotdeb and MySQL Connector/J version is 5.0.3.
Well, it turned out it was actually an issue with unclosed prepared statements.
When opened statements count at MySQL server reached its allowed maximum, application was still able to continue working somehow, withoout producing sql error:
Error Code: 1461 Can’t create more than max_prepared_stmt_count statements
But in that mode it started to wrap boolean values with quotes, causing all my troubles affecting BIT(1) columns.

java web service working with PostgreSQL database

my code is written in java, and I am really new to java, so i hope my explanations are correct:
i have a java written web service that works with a data base.
the data base types can be PostgreSQL and mysql.
so my webservice works with the JDBC connection for both data bases.
one of my data base tables is table urls,
for postgressql it is created like this:
CREATE TABLE urls (
id serial NOT NULL primary key,
url text not null,
type integer not null);
for mysql it is creates like this:
CREATE TABLE IF NOT EXISTS URLS (
id INTEGER primary key NOT NULL AUTO_INCREMENT,
url varchar (1600) NOT NULL,
type INTEGER NOT NULL );
when I try inserting data to this table I use an entity called urls:
this entity has:
private BigDecimal id;
private String url;
private BigInteger type;
when I try to insert values to the urls table I assign values to the urls entity, while leaving the id as NULL since it is AUTO_INCREMENT for mysql and serial for postgres.
the query works for my sql, but fails for postgress.
in the postgres server log I can see the following error:
null value in column "id" violates not-null constraint
cause I sends NULL as the id value.
I found out that in order for the query to work I should use this query:
INSERT INTO URLS(ID, TYPE, URL) VALUES(DEFAULT, 1, 'DED'); or this one:
INSERT INTO URLS(TYPE, URL) VALUES(1, 'DED'); or this one:
instead of this one, that I use:
INSERT INTO URLS(ID, TYPE, URL) VALUES(NULL, 1, 'DED');
so my question is,
how do I assign the DEFAULT value to a BigDecimal value in java ?
is removing the id from my entity is the right way to go ?
how can I make sure that any changes I do to my code wont harm the mysql or any other data base that I will use ?
If you specify the column name in the insert query then postgres does not take the default value. So you should use your second insert query.
INSERT INTO URLS(TYPE, URL) VALUES(1, 'DED');
This syntax is correct for both postgres and MySQL.
This should resolve your question (1) and (3). For (2) DO NOT delete the id field from your entity. This id is going to be your link to the database row for a specific object of the entity.
1 - I think it is proper to use Long or long types instead of BigDecimal for id fields.
2 - Yes it generally helps, but it lowers portability. BTW, using an ORM framework like Hibernate may be a good choice.
3 - Integration testing usually helps and you may want to adopt TDD style development.
When using this statement:
INSERT INTO URLS(ID, TYPE, URL) VALUES(NULL, 1, 'DED');
you are telling the database that you want to insert a NULL value into the column ID and Postgres will do just that. Unlike MySQL, PostgreSQL will never implicitely replace a value that you supply with something totally different (actually all DBMS except MySQL work that way - unless there is some trigger involved of course).
So the only solution to is to actually use an INSERT that does not supply a value for the ID column. That should work on MySQL as well.

Categories