I have data in a mySQL database table. I am selecting this data and trying to insert it to a Netezza database table. I am using the spring framework and have a entity class called Student.
Some of the fields in the mySQL database table are in Integer format but the equivalent field in Netezza is in character format.
I am using a JDBC template and getting the data from mySQL and inserting that Student object to Netezza.
Here is my method:
String sqlStudent="INSERT INTO STUDENT(STUDENTID,CLASSID,COURSEID,TESTDATE,SCOREDATE) VALUES (?,?,?,?,?)";
netezzaJDBCTemplate.update(sqlStudent,new Object[] {student.getStudentId(),student.getClassId(),student.getCourseId(),student.getTestDate(),student.getScoreDate)});
I get an error when I do this. I even tried hard coding the INSERT.
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO STUDENT(STUDENTID,CLASSID,COURSEID,TESTDATE,SCOREDATE) VALUES (1521995,134,21,'2014-02-15 00:00:00','2014-02-15 00:00:00') )]; nested exception is org.netezza.error.NzSQLException: Parameter Index out of range: 1
Is this because of the difference in the column data types between the 2 databases? or am I missing something else?
Please help.
new studentMapper() might be the issue. JdbcTemplate's update method wont accept RowMapper correct?
If your are not using NamedParameterJdbcTemplate try to prefer that over regular JdbcTemplate which lets you bind the sql params with names.
Related
I am using a single Spring JDBC update to make an update to two tables in my Postgres database. My SQL query is as follows:
UPDATE accounts SET last_transaction_amount = :transaction_amount WHERE acct_num = :acct_num; INSERT INTO transactions (transaction_amout) VALUES (:transaction_amount);
Using NamedParameterJdbcTemplate#update, I have no issue executing this query and achieving the expected results.
The transactions table generates a sequential transaction identifier, and I want to return this to my application.
I've tried passing a GeneratedKeyHolder in the update call. This is returning the error "A result was returned when none was expected". Docs link.
I've tried passing a GeneratedKeyHolder and array of column names (new String[] {"transaction_id"}). This is returning the error that the column doesn't exist. Note this method call does work to return the transaction id when I only pass the INSERT query without the preceding UPDATE query. Docs link.
How can I retrieve the generated key? Thank you!
You seem to be looking for the RETURNING clause. Assuming that the serial number is called transaction_id:
INSERT INTO transactions (transaction_amout)
VALUES (:transaction_amount)
RETURNING transaction_id;
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
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');
I have an Oracle table that has a CLOB in it. Inside this CLOB can be a SQL statement. This can be changed at any time.
I am currently trying to dynamically run these SQL statements and return the column names and data back. This is to be used to dynamically create a table on the web page.
Using Hibernate, I create the query and get the data like so:
List<Object[]> queryResults = null;
SQLQuery q = session.createSQLQuery(sqlText);
queryResults = q.list();
This gets the data I need, but not the column names. I have tried using the getReturnAliases() method, but it throws an error that the "java.lang.UnsupportedOperationException: SQL queries do not currently support returning aliases"
So my question is: Is there a way through Hibernate to get these values dynamically?
You can use :
q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> aliasToValueMapList=query.list();
to get column names in createSQLQuery.
For more details please refer to this question.
You can use the addScalar method to define the columns.
Look at 16.1.1
https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html
You could implement a ResultTransformer ( http://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/transform/ResultTransformer.html ) and set it on the native query. I think with a native SQL query you get the aliases as specified in the SQL as alias parameter in the callback method.
In 2018 I would suggest using NativeQueryTupleTransformer with native queries.
query.setResultTransformer(new NativeQueryTupleTransformer());
The result format is List<Tuple>. This format is very convenient to work with native SQL queries.
I want to run a native SQL from a file using Hibernate. The SQL can contain several statements creating the database structure (i.e. tables, constraints but no insert/update/delete statements).
Example, very simple query is below (which contains the following two SQL statements)
CREATE DATABASE test;
CREATE TABLE test.testtbl( id int(5));
I am using MySQL db, and when I run the above query I am gettng syntax error returned. When I run them one by one, its ok.
Caused by: 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
'CREATE TABLE test.testtbl( id int(5))' at line 1
The code to run the query is below (above statement is assigned to 'sql' variable):
session = sf.openSession();
session.beginTransaction();
Query qry = session.createSQLQuery(sql);
qry.executeUpdate();
session.getTransaction().commit();
Any help would be appreciated.
As others have explained
You must run these queries one by one.
The hibernate code gets translated into running one update statement on JDBC.
But you provided two update statements.
In addition,
I personally prefer to have the code that creates tables outside of the Java application, in some DB scripts.
The parameters of the method createSQLQuery is t-sql code;
t-sql code to ensure that in the mysql interface analyzer correctly.
You can try changed the sql :'CREATE TABLE testtbl(id int(5));'
by the way you can use JDBC Connection api (Don't recommend to do so)
Such as:
java.sql.Connection conn=session.connection();