Getting Error : SQLErrorCodes loaded: Spring jdbc connection - java

I am getting below error when I am trying to insert row in database and also while calling prepared statement:
INFO XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
07:05:53,727 INFO SQLErrorCodesFactory:126 - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]
Also below is insert statement:
String sql = " INSERT INTO customer_Table (customer_no ,customer_name ,address_no ,phone_no"
+ " ,email_addr ,customer_type_code ,city_code ,language_code ,input_user_id ,input_timestamp ,last_update_user_id ,last_update_timestamp"
+ ") VALUES ( '"
+ customerNumber2
+ "' ,UPPER('"
+ getTrimmedString(customerName,300)
+ "') , '"
+ addSeqNum2
+ "'"
+ ",'"
+ processForNull(getTrimmedString(helperObject.getData().getVisitPhone(),30))
+ "','"
+ processForNull(getTrimmedString(helperObject.getData()
.getVisitEmailAddress(),256))
+ "','001','"
+ helperObject.getCityCode()
+ "', 'en','SYSTEM',SYSDATE+-1/24,'SYSTEM',SYSDATE+-1/21)";
jdbcTemplate.update(sql);
Because of this error code is not executing completely. I am also not getting full stack of error.
Can anyone help me please.

Length of background parameter, exceeding the length defined by the field in the database
The data type of descendant parameters conflicts with the data type of the field in the database

Related

Jpa native query doesnt work with group by case/when statement with binding values

Iam trying to use Jpa repository to get data from my sql server using a native query
This is a simple call from my service
repo.testData("h3","h3");
This is my repository query.
Select statement can read the binding variable :level but group by is unable to read it.
#Query(value="SELECT sum(pos.total_weekly_sales) as curr_yr_sales, sum(pos.total_weekly_qty) as curr_yr_qty, pos.vendor_nbr,pos.gmm_id,\n" +
"case \n" +
"when :level = 'h3' then pos.category_id\n" +
"else 0\n" +
"end category_id\n" +
"from dbo.agg_sams_data pos\n" +
"join dbo.calendar_dim cal on pos.wm_year_wk_nbr = cal.wm_year_wk_nbr\n" +
"WHERE \n" +
"cal.calendar_date BETWEEN '2019-09-11' and '2020-09-09'\n" +
"and pos.vendor_nbr = 68494\n" +
"and pos.gmm_id = 45\n" +
"and (:h3Flag = 'N' or pos.category_id = 52)\n" +
"GROUP by pos.vendor_nbr,pos.gmm_id,\n" +
"case \n" +
"when :level='h3' then pos.category_id\n" +
"else 0\n" +
"end",nativeQuery = true)
List<List<Double>> testData(String level,String h3Flag);
And i get the following error
com.microsoft.sqlserver.jdbc.SQLServerException: Column 'dbo.agg_sams_data.category_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
If i pass the hardcoded value in the group by clause it works fine(as below)
"GROUP by pos.vendor_nbr,pos.gmm_id,\n" +
"case \n" +
"when 'h3'='h3' then pos.category_id\n"
You should try putting pos.category_id into the group by instead of the whole case when statement. The problem is, that SQL Server can't be sure that the parameter in both cases will have the same value so the expressions could be different.

Create Statement Returning ERROR: syntax error at or near "RETURNING"

I want to create a database table with a CREATE statement. I get an error Saying
Error: syntax error at or near "RETURNING".
I understand there is some sort of bug with the JDBC driver. As I found this.
Postgres JDBC driver: PSQLException: syntax error at or near RETURNING
It seems that I need to set Quirk Mode. But I'm not sure how to do that.
Right Now I have
Connection dbConnection;
dbConnection = DriverManager.getConnection(connectionString,username,password);
Statement st = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
st.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
I dont know where I am supposed to set quirk mode
EDIT:
I'm sorry for missing details. It took me through the guided way.
The statement is made through
st.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
And the SQL is
String employeeTable="CREATE TABLE \"employee\" (\n" +
" \"employee_id\" serial,\n" +
" \"employee_first_name\" TEXT,\n" +
" \"employee_middle_name\" TEXT,\n" +
" \"employee_last_name\" TEXT,\n" +
" \"employee_dob\" date ,\n" +
" \"employee_ssn\" TEXT NOT NULL DEFAULT '0',\n" +
" \"employee_wages\" FLOAT(30) NOT NULL DEFAULT '0',\n" +
" \"employee_password\" TEXT DEFAULT '0',\n" +
" \"employee_issupervisoer\" BOOLEAN NOT NULL DEFAULT 'false',\n" +
" \"employee_hassupervisoer\" BOOLEAN NOT NULL DEFAULT 'false',\n" +
" \"employee_supervisor_id\" integer,\n" +
" \"employee_clockstatus\" BOOLEAN DEFAULT 'false',\n"+ // True = IN : False = OUT
" \"employee_lastpunch\" timestamp, \n"+
" \"employee_isactive\" BOOLEAN, \n"+
" CONSTRAINT employee_pk PRIMARY KEY (\"employee_id\")\n" +
") WITH (\n" +
" OIDS=FALSE\n" +
");\n";
Honestly I don't think that SQL matters though. This statement worked for me about 6 months back. I dont know what changed but I changed from Postgresql 9.4 to 10.7? whatever the most recent 10.x stable is. and I updated my Gradle to
// https://mvnrepository.com/artifact/org.postgresql/postgresql
compile group: 'org.postgresql', name: 'postgresql', version: '42.2.6'
You can not combine a CREATE TABLE statement with a RETURNING clause (as it does not "return" anything).
When you call executeUpdate(query,Statement.RETURN_GENERATED_KEYS) you are requesting the generated keys from a DML statement to be returned. The Postgres JDBC driver does this by adding a RETURNING clause to the query - which obviously makes no sense with a DDL statement.
Use execute(query) instead.
Or executeUpdate(query) (without requesting generated keys)

How to put a real values in SQL query using postgreSQL?

I have some problems with an application developed in Java that uses postgreSQL as a DB. I managed to make a dummy query as follows:
String sql = "INSERT INTO voicemessages (UNIQUEID,MSGNM,DIR,CONTEXT,MACROCONTEXT,CALLERID, ORIGTIME,DURATION, FLAG,MAILBOXUSER,MAILBOXCONTEXT,RECORDING, LABEL, read ) "
+ "VALUES (1, 1, 'dir/dir1/msgs', 'message', 'message', '6001', '15/01/2015 13:31:25', '1:32', 'flag', 'Georgi Georgiev', 'Georgi Georgiev', '12314124', 'some label', false);";
And it works perfect when I execute the statement. A row in the DB is created and I am able to display the data using:
SELECT * FROM voicemessages;
The problem is when I create my own VoiceMail class and when I create an object from this type and put in the query the getters and setters for this object I receive some kind of an error:
org.postgresql.util.PSQLException: ERROR: column "dir" does not exist Hint:There is a column named "dir" in table "voicemessages", but it cannot be referenced from this part of the query.Position: 169
I am trying to insert a row by using and executing this:
String sql = "INSERT INTO voicemessages (UNIQUEID,MSGNM,DIR,CONTEXT,MACROCONTEXT,CALLERID, ORIGTIME,DURATION, FLAG,MAILBOXUSER,MAILBOXCONTEXT,RECORDING, LABEL, read ) "
+ "VALUES (" + message01.getUniqueId() + ", " + message01.getMessageNumber() + ", " + message01.getDirectory() + ", " + message01.getContext() + ", " + message01.getMacroContext() + ", " + message01.getCallerId() + ", " +message01.getOrigTime() + ", " + message01.getDuration() + ", " + message01.getFlag() + ", " + message01.getMailboxUser() + ", " +message01.getMailboxContext() + ", " + message01.getRecording() + ", " + message01.getLabel() + ", " + message01.getRead()+ ");"+" ";
Any help or suggestion is appreciated.
Thank you in advance!
Do not use Direct values use parameters for safety, What happens is that the SQL statement you passĀ is parsed to prepare and compiled by the database. So by sending the actual SQL separately from the parameters, you limit the risk of SQL injection

Unable to insert record in MySql using JAVA

I am new to Java and MYSql in fact using this combination first time and facing real trouble. I want to insert few records in a table but unable to do so. Following are the fields and datatype in the table named tbl_cdr in MySql.
**Field** **Type**
DATEANDTIME datetime NULL
VALUE1 int(50) NULL
VALUE2 varchar(50) NULL
VALUE3 varchar(50) NULL
VALUE4 varchar(50) NULL
VALUE5 varchar(50) NULL
The record I want to insert contains following values
2014-05-19 02:37:18, 405, MGW190514023718eab4, 923016313475, IN, ALERTSC
I am using following query and statements to Insert record in table
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", " + columnsList.get(2) + ", " + columnsList.get(3) + ", " + columnsList.get(4) + ", " + columnsList.get(5) + ")";
try
{
Statement qryStatement = conn.createStatement();
qryStatement.executeUpdate(sqlQuery);
qryStatement.close();
} catch (SQLException ex)
{
Logger.getLogger(CdrProject.class.getName()).log(Level.SEVERE, null, ex);
}
But when I reach the statement qryStatement.executeUpdate(sqlQuery); exception is thrown as:
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 '02:37:18, 405, MGW190514023718eab4,
923016313475, IN, ALERTSC)' at line 1
value2 ,value3 ,value4 and value 5 are varchars so it should be written within ''.
Do like this
sqlQuery = "INSERT INTO tbl_cdr (DATEANDTIME,VALUE1,VALUE2,VALUE3,VALUE4,VALUE5)" + "VALUES ("+ forDateAndTime.format(date) + ", " + columnsList.get(1) + ", '" + columnsList.get(2) + "',' " + columnsList.get(3) + "',' " + columnsList.get(4) + "',' " + columnsList.get(5) + "')";
You're inserting the date incorrectly. MySQL allows you to insert a string literal or a number.
You're trying to use 02:37:18 as a number, when really you should be using it as a string literal: '02:37:18'
Here is the MySql Reference describing this.
You're also not treating your varchars as strings either, they should be enclosed with quotes.

Hibernate Interceptor - Try-Catch T-SQL

I have the requirement to ignore primary key violations from SQL Server in my inserts. While there are several ways to accomplish this task, many of them have performance implications or are not feasible. I need to batch insert into a table and there is a possibility of duplicates.
To accomplish the task, I've written a Hibernate interceptor that intercepts onPrepareStatement and wraps the Hibernate generated SQL in a t-SQL TRY CATCH construct. The TRY CATCH looks for primary key violations and silences them. Below is my code for the interceptor.
private static final String FORMAT_TRY_CATCH = "BEGIN TRY %s END TRY\r\n" + "BEGIN CATCH\r\n" + "\r\n"
+ "DECLARE #ErrorMessage NVARCHAR(4000),\r\n" + " #ErrorNumber INT,\r\n" + " #ErrorSeverity INT,\r\n" + " #ErrorState INT,\r\n"
+ " #ErrorLine INT,\r\n" + " #ErrorProcedure NVARCHAR(200) ;\r\n" + "\r\n"
+ "SELECT #ErrorNumber = ERROR_NUMBER(), #ErrorSeverity = ERROR_SEVERITY(),\r\n"
+ " #ErrorState = ERROR_STATE(), #ErrorLine = ERROR_LINE(),\r\n"
+ " #ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-') ;\r\n" + "\r\n"
+ "SELECT #ErrorMessage = N'Error %%d, Level %%d, State %%d, Procedure %%s, Line %%d, ' +\r\n"
+ " 'Message: ' + ERROR_MESSAGE() ;\r\n" + " IF #ErrorNumber <> 2627\r\n" + " BEGIN\r\n"
+ "RAISERROR (#ErrorMessage, #ErrorSeverity, 1, #ErrorNumber, -- parameter: original error number.\r\n"
+ " #ErrorSeverity, -- parameter: original error severity.\r\n" + " #ErrorState, -- parameter: original error state.\r\n"
+ " #ErrorProcedure, -- parameter: original error procedure name.\r\n"
+ " #ErrorLine-- parameter: original error line number.\r\n" + " ) ;\r\n" + " END\r\n" + "END CATCH;";
#Override
public String onPrepareStatement(String sql) {
if (sql.toLowerCase().startsWith("insert")) {
return String.format(FORMAT_TRY_CATCH, sql);
}
return sql;
}
The interceptor works except that when there is a primary key constraint violation the statement returns 0 affected rows. Hibernate has a check that throws an exception if the number of affected rows doesn't match the expected number of rows. I can work around the issue by executing a dummy t-SQL statement that returns one affected row.
DECLARE #dummy TABLE (col1 int)
INSERT INTO #dummy values (1)
This dummy logic will decrease the performance when there is a primary key constraint violation. Is there a better performing dummy script, or a better way to catch primary key constraint violations?
Note: doing a select before each insert is not acceptable for performance reasons. I cannot recreate my SQL's primary key to turn on IGNORE_DUP_KEY.

Categories

Resources