How to use RowMapper to insert record into table? - jdbctemplate
How to insert data into table using row mapper?
I am trying this:
Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,salary) VALUES(10,'ABC',12333);",new BeanPropertyRowMapper<Employee>(Employee.class));
It gives me bad SQL grammar error.
But query works in SQL developer. What I am doing wrong?
Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [INSERT INTO employee(id, name,salary) VALUES(99,'ABC',12333)]; nested exception is java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:411)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:466)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:476)
at com.cts.orm.rowmapper.Test.main(Test.java:29)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:600)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
at oracle.jdbc.driver.T4C8Odscrarr.doODNY(T4C8Odscrarr.java:98)
at oracle.jdbc.driver.T4CStatement.doDescribe(T4CStatement.java:805)
at oracle.jdbc.driver.OracleStatement.describe(OracleStatement.java:3978)
at oracle.jdbc.driver.OracleResultSetMetaData.<init>(OracleResultSetMetaData.java:55)
at oracle.jdbc.driver.OracleResultSetImpl.getMetaData(OracleResultSetImpl.java:175)
at org.springframework.jdbc.core.BeanPropertyRowMapper.mapRow(BeanPropertyRowMapper.java:240)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:455)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:400)
... 3 more
NamedParameterJdbcTemplate does what you want:
namedParameterJdbcTemplate.update(
"INSERT INTO employee(id, name, salary) VALUES (:id, :name, :salary)",
new BeanPropertySqlParameterSource(Employee.class));
removing the semi colon at the end of the statement should solve the problem use it like this. when using the jdbc templates it is not good to use semicolon at the end of sql statements
Employee user1 = jtemplate.queryForObject("INSERT INTO employee(id, name,salary) VALUES(10,'ABC',12333)",new BeanPropertyRowMapper<Employee>(Employee.class));
try using it like
jtemplate.update("INSERT INTO Employee(ID, NAME, Salary) VALUES (?, ?, ?)",
new Object[] { employee.getId(), employee.getName(), employee.getSalary() });
i am using this and it works correctly and displays no errors
Try this:
jdbcTemplate.update("INSERT INTO employee(id, name,salary) VALUES(?,?,?)", 10, "ABC", 12333);
Related
Android SQLITE Insert into table with values coming from a subquery
In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery. The insert into statement may look like the following example: INSERT INTO MyTable (field_1, field_2) VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...)) At present I am doing it manually building the query: String MyQuery = "INSERT INTO mytable (field_1, field_2) VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String SQLiteDatabase= db = getWritableDatabase(); db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock What i would like to do instead is: SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put("field_1", "value for field 1"); values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)")); db.insert("MyTable", null, values); db.close(); Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement. Is there a way to achieve this?
The whole point of the ContentValues container is to be able to safely use strings without interpreting them as SQL commands. It is not possible to use subqueries with insert(). The only way to get a value from another table is by executing a separate query; in this case, ThisIsAQuery() would be stringForQuery() or longForQuery().
Teradata : How to get the server name using query
How can I get the server name using query in Teradata? That is, if I am writing a query on the 'dev' server, it should return the dev server name. for example, in Sybase : we will be using select ##servername.
There's nothing like ##servername in TD. You might create a SQL UDF on each server returning the name, e.g. REPLACE FUNCTION syslib.#servername () RETURNS VARCHAR(30) LANGUAGE SQL CONTAINS SQL DETERMINISTIC RETURNS NULL ON NULL INPUT SQL SECURITY DEFINER COLLATION INVOKER INLINE TYPE 1 RETURN 'dev' If it's created in syslib it can be accessed without qualifying it like this: SELECT #servername();
SELECT CASE WHEN LogonSource LIKE '%UAT%' THEN 'UAT' WHEN LogonSource LIKE '%PROD%' THEN 'Prod' ELSE 'Unknown' END DatabaseName FROM DBC.SessionInfoV WHERE UserName = 'myname';
This will give you information close to ##servername. select ClientTdHostName, ServerIPAddrByServer, ServerPortByServer from DBC.SessionInfo where SessionNo=Session; Validated against 17.xx TD.
Sqlite DB Error - could not prepare statement
I am getting following error on insert statement for sqlite DB could not prepare statement (1 near "undefined": syntax error) I tried 2 variations of insert, for both error is same var sql = "INSERT INTO Med(MedID) VALUES(?),"; sql += "['"+dataObj[i].MedID+"']"; var sql = "INSERT INTO Med(MedID) VALUES ('"+dataObj[i].MedID+"')"; tx.executeSql(sql);
The correct way to give parameters to an SQL statement is as follows: var sql = "INSERT INTO Med(MedID) VALUES (?)"; tx.executeSql(sql, [dataObj[i].MedID]);
It looks like you are missing the space that is needed between the table name and the column names. Try this: var sql = "INSERT INTO Med (MedID) VALUES ('"+dataObj[i].MedID+"')"; tx.executeSql(sql); Make sure your dataObj[i].MedID is also defined. Add a console.log(sql) before your executeSql statement to check the command before using it.
How to insert a string containing '%' using QSqlQuery?
I am trying to insert a string which contains '%' using QsqlQuery but I am always getting an error of type QSqlError::TransactionError with the message "near "%": syntax error Unable to execute statement" I have tried several ways to escape the "%" but I am still getting that error message. Please see the code snippet below. query.exec(QString("INSERT INTO my_table (name, address) VALUES (\"%1\", \"%2\")") .arg("Harry", "#302%%1,...")); In place of "%%", I have tried "\%", "\%", but still it didn't work and I am having the same error message.
In SQL, strings are delimited with ', not ". Anyway, you should use parameters: query.prepare("INSERT INTO my_table (name, address) VALUES (?, ?)"); query.addBindValue("Harry"); query.addBindValue("#302%%1,..."); query.exec();
SQLite Syntax Error
I made a sql query, below. I am getting an exception which I have shown as well. Any help is appreciated. QUERY: INSERT OR REPLACE INTO CLAIMS (DATE ,TIME , ADDRESS , CITY, STATE , POSTAL , PHFNAME ,PHLNAME ,PHEMAIL ,PHPHONE ,AGENCY ,POLICY ,VEHICLENAME, YEAR ,MAKE ,MODEL ,PLATELICENSE ,LSTATE ,VIN ,DRIVERNAME,DRFNAME ,DRLNAME , DRPHONE ,DREMAIL ,DRLICENSE) VALUES("Wednesday, May 4, 2011", "10:39:10 PM EDT", "400 Chatham","Pune", "Penn", "45223", "John", "Richard","jsmith#newyahoo.com","+1-11111111111", "Three Rivers Insurance","(null)", "(null)", "(null)", "(null)", "(null)","(null)", "(null)", "(null)","(null)", "(null)", "(null)","(null)", "(null)","(null)") WHERE DATE LIKE 'Wednesday, May 4,%' AND TIME = '10:39:10 PM EDT' Error: SQLiteManager: Likely SQL syntax error: [ near "WHERE": syntax error ] Exception Name: NS_ERROR_FAILURE Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [mozIStorageConnection.createStatement]
I faced the same issue for sync table for insert and update at a time and finally i use. To use the insert or replace statement you need to use the coalesce function that required primary key column to put the where clause. COALESCE((SELECT PRIMARY_KEY_COLUMN FROM TABLE_NAME WHERE UNIQUE_COLUMN = 'VALUE'), (SELECT MAX(PRIMARY_KEY_COLUMN)+1 FROM TABLE_NAME)) it worked for me e.g INSERT OR REPLACE INTO TBL_ADDRESSES (ADDRESS_ID,ADDRESS1,ADDRESS2,ADDRESS3,ADDRESS_NAME,CITY,DB_ID) VALUES ( COALESCE((SELECT ADDRESS_ID FROM TBL_ADDRESSES WHERE DB_ID = '111'), (SELECT MAX(ADDRESS_ID)+1 FROM TBL_ADDRESSES)), 'IT 27','Pratap DSFSDSDDSDSF','test add ','IT 27','Jaipur','111') ;
INSERT OR REPLACE doesn't support WHERE clause, see theSQLite Insert doc. You can use a WHERE clause in UPDATE statements, see the SQLite Insert doc Can help you if you can let us know what you wanted here ?