SQLite Syntax Error - sqlite

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 ?

Related

INSERT INTO with subquery and ON CONFLICT

I want to insert all elements from a JSON array into a table:
INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
WHERE value LIKE '%'
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;
This works so far, but do I really need the WHERE value LIKE '%' clause?
When I remove it:
INSERT INTO local_config(parameter, value)
SELECT json_extract(j.value, '$.parameter'), json_extract(j.value, '$.value')
FROM json_each(json('[{"parameter": 1, "value": "value1"}, {"parameter": 2, "value": "value2"}]')) AS j
ON CONFLICT (parameter) DO UPDATE SET value = excluded.value;
I get this error:
[SQLITE_ERROR] SQL error or missing database (near "DO": syntax error)
From SQL As Understood By SQLite/Parsing Ambiguity:
When the INSERT statement to which the UPSERT is attached takes its
values from a SELECT statement, there is a potential parsing
ambiguity. The parser might not be able to tell if the "ON" keyword is
introducing the UPSERT or if it is the ON clause of a join. To work
around this, the SELECT statement should always include a WHERE
clause, even if that WHERE clause is just "WHERE true".
So you need the WHERE clause, but it can be a simple WHERE true or just WHERE 1.

In SQLite , How to SELECT a column only if it exists in the table

I am trying to write a query where the table will be generated dynamically for each job . And the columns will either exist or not based on input. In SQLite , i need to fetch the value of a column only if it exists otherwise null.
I tried with if & case statements using Pragma_table_info , but for negative scenario it is not working.
'''select
case when (select name from pragma_table_info('table_name') where name = col_name )is null
then error_message
else col_name'''
end
from table_name
This query is running if the mentioned col_name exists . But if not exists then it is throwing syntax error in else part.
Only in select query it should be done
Your code should work if the table's name, the column's name and the error message are properly quoted:
SELECT CASE
WHEN (SELECT name FROM pragma_table_info('table_name') WHERE name = 'col_name')
IS NULL THEN 'error_message'
ELSE 'col_name'
END
But you can do the same simpler with aggregation and COALESCE():
SELECT COALESCE(MAX(name), 'error_message')
FROM pragma_table_info('table_name')
WHERE name = 'col_name'
See the demo.

Creating a new table in sqlite database [duplicate]

I'm having some strange feeling abour sqlite3 parameters that I would like to expose to you.
This is my query and the fail message :
#query
'SELECT id FROM ? WHERE key = ? AND (userid = '0' OR userid = ?) ORDER BY userid DESC LIMIT 1;'
#error message, fails when calling sqlite3_prepare()
error: 'near "?": syntax error'
In my code it looks like:
// Query is a helper class, at creation it does an sqlite3_preprare()
Query q("SELECT id FROM ? WHERE key = ? AND (userid = 0 OR userid = ?) ORDER BY userid DESC LIMIT 1;");
// bind arguments
q.bindString(1, _db_name.c_str() ); // class member, the table name
q.bindString(2, key.c_str()); // function argument (std::string)
q.bindInt (3, currentID); // function argument (int)
q.execute();
I have the feeling that I can't use sqlite parameters for the table name, but I can't find the confirmation in the Sqlite3 C API.
Do you know what's wrong with my query?
Do I have to pre-process my SQL statement to include the table name before preparing the query?
Ooookay, should have looked more thoroughly on SO.
Answers:
- SQLite Parameters - Not allowing tablename as parameter
- Variable table name in sqlite
They are meant for Python, but I guess the same applies for C++.
tl;dr:
You can't pass the table name as a parameter.
If anyone have a link in the SQLite documentation where I have the confirmation of this, I'll gladly accept the answer.
I know this is super old already but since your query is just a string you can always append the table name like this in C++:
std::string queryString = "SELECT id FROM " + std::string(_db_name);
or in objective-C:
[#"SELECT id FROM " stringByAppendingString:_db_name];

How to use RowMapper to insert record into table?

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);

Syntax error in INSERT INTO statement in MS Access 2010

Im using Access 2010 when I try to input this syntax:
INSERT INTO Order ( ClientId, ProductID, EmployeeID, DeliveryID )
VAlUES ('1', '8', '3' '1');
It says syntax error in insert order statement. I used the same syntax in inserting record to my other tables and it works.
It's just a missing comma between the 2 last arguments.
Bye!

Resources