How do I get a NULL into this SQLite insert statement? - objective-c

I have 3 SQLite tables. Each has an ID as primary key; if I provide a NULL when inserting a record to ID, it will auto-increment the key (at least that's what the SQLite docs say). I am trying to get the NULL into this insert statement, but it crashes ('NSInvalidArgumentException', reason: '* -[NSPlaceholderString initWithFormat:locale:arguments:]: nil argument'
). Here is a snippet of the statement (dbCmd is defined as NSString):
dbCmd = #"INSERT INTO CustData (ID, BUS_NAME, EMAIL, PHONE, SHOP_NAME, SHOP_ADDR1, SHOP_ADDR2, SHOP_CITY_STATE, SHOP_ZIP, "
"SHIP_NAME, SHIP_ADDR1, SHIP_ADDR2, SHIP_CITY_STATE, SHIP_ZIP, SALES_NAME, NOTES) VALUES('";
dbCmd = [dbCmd stringByAppendingFormat:NULL]; // <--------------------
dbCmd = [dbCmd stringByAppendingString: [methodParameters objectForKey: #"businessName"]];
dbCmd = [dbCmd stringByAppendingString: #"', '"];
dbCmd = [dbCmd stringByAppendingString: [methodParameters objectForKey: #"email"]];
How do I fix this?

From the sqlite docs:
If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.
http://www.sqlite.org/autoinc.html
If you have no specific reason to specify the ID, you can simply leave it out!

Related

How to put SQL query in Spring boot application in if function?

In my spring boot application in REQUEST i post streamName and in response I get key. I'm putting this into a database and I want to avoid repeating stream names. My plan is to add such query to the insertStream method and when it returns null value, i.e. there is no such name in the database, then INSERT will be performed. Unfortunately I do not know how to implement this in the code.
This is my method:
#Override
public int insertStream(String key, String streamName) {
String sql = "" +
"INSERT INTO stream (" +
" stream_name, " + " license_key )" + "VALUES (?,?)";
return jdbcTemplate.update(
sql,
streamName,
key
);
}
and this is mention example query:
SELECT count(*) FROM public.stream WHERE stream_name='live2';
but instead of live2 it will be streamName parameter
you can use upsert in postgrsql
add a unique constraint to the stream_name column
CREATE UNIQUE INDEX unq_stream_name on stream(stream_name);
ALTER TABLE stream
ADD CONSTRAINT unq_stream_name_const
UNIQUE USING INDEX unq_stream_name;
then do upsert:
insert into stream (stream_name, license_key)
values (?,?) on conflict do nothing;
if the stream_name already exists , nothing will be inserted.

java sql return id from insert query

I have the next SQL template:
INSERT_QUERY = "INSERT INTO "article" (article_table, article_id) VALUES ({1}, {2}) RETURNING article_id";
I can not change this template. The task is to return id from sql base. What I have done:
PreparedStatement insert_query = db.prepareStatement(String.format(INSERT_QUERY, table, id));
insert_query.executeUpdate();
ResultSet result_id = insert_query.getGeneratedKeys();
if(result_id.next()){
id = result_id.getInt(1);
}
System.out.println(this.id);
But this code do insert values but not return nothing((
Exception in thread "main" org.postgresql.util.PSQLException: A
result was returned when none was expected.
If I change to:
db.prepareStatement(String.format(INSERT_QUERY, table, id), PreparedStatement.RETURN_GENERATED_KEYS);
The sql query becomes:
INSERT INTO "article" (article_table, article_id)
VALUES ({1}, {2}) RETURNING article_id RETURNING *
which is invalid.
So my question is there any way I can use existing template to return id or eventually I need to change it?

INSERT statement sqlite3 objective-c

Hopefully my question has a simple solution. I am just starting to use sqlite3 and I have created a database called local and a table called table with 1 column called name with type text.
It connects to the database fine its just I am trying to input a string value into the tables column but I think there is an issue with my INSERT text. I know its probably something simple if anyone could just let me know where I went wrong. Thanks.
SString *inserStmt = [NSString stringWithFormat:#"INSERT INTO TABLE(NAME) VALUES ('%s')", [key UTF8String]];
const char *insert_stmt = [inserStmt UTF8String];
sqlite3_exec(database, insert_stmt, NULL, NULL, NULL);
Your first problem is that you ignore any errors and don't display the error message, so if something goes wrong, you will have no clue.
Your second problem is that TABLE is a keyword;
to use it as a name in SQL statements, you have to escape it with double quotes:
INSERT INTO "TABLE"(NAME) VALUES('...')

SQlite: select with insert if not exist

Let's suppose we have a table defined with:
CREATE TABLE IF NOT EXISTS signals(sigid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)
This table initially is empty.
I would like to get the sigid for a given name with a select and in case name does not exist, add it and get the new autoincremented id.
I would like to use this query in order to autogenerate ,when needed, a new id that is used as foreign key in another table. I must put attention to the performances so I cannot proceed as :
check if name is present and return id witha a SELECT
if returned id is null create a new entry with an INSERT
get the new id again with a new SELECT
Is it possible do it with a single SELECT-like query ?
Thanks!
i think with an single select no.
Let's say i want to insert id_build = 3, hashed_value = 1 into the big table 'crash'.
The code in example makes first select to check if the value was already in the table, if yes skips the insert with where .. is null then retrive the id from already saved into temporary table.
example :
create temporary table if not exists Variablez(Name TEXT primary key on conflict replace, Value TEXT); --storing vars
insert into Variablez(Name, Value) values ('tmp_id', (select id_crash from crash where hashed_value = "1" )); --put id if was existing
insert into crash(id_build, hashed_value) select 3, 1 where (select Value from Variablez where Name = 'tmp_id' ) is null; -- insert if not exists
select
case
when (select Value from Variablez where name = 'tmp_id' ) is null then
'0'
else
'1'
end
as existing,
case
when (select Value from Variablez where name = 'tmp_id' ) is null then
(select id_crash from crash where hashed_value = "1")
else
(select Value from Variablez where name = 'tmp_id')
end
as id_returned;
if the table is empty and you are the one filling it in just one shot (and you don't need to do it again later on when there is data in the table), AND you don't have too many rows, then you could just cache the names you have already inserted and look them up in memory.
It's more of a comment, I guess.
there is also this for getting the last inserted id:
SELECT last_insert_rowid();
But if the above applies, you are even faster by assigning the ids yourself, and not define it as AUTOINCREMENT. Then you don't need to get the last inserted id, you just keep a counter and all the names inserted and increment for each new name you find.
CREATE TABLE IF NOT EXISTS signals(sigid INTEGER PRIMARY KEY NOT NULL, name TEXT)
List<String> insertedNames = new List<String>();
int count = 0;
while(input.hasNext())
{
String name = input.next();
if( !insertedNames.contains(name) )
{
var sql = "insert into table (sigid,name) VALUES (" + count + ", " + name + ")";
executeSql(sql);
insertedNames.add(name);
count++;
}
}
answering your comment
public int getId( string name )
{
String sql = "select id from table where name='" + name + "'";
int theIdForTheName = executeAndGetFirstColumnAsInt(sql);
return theIdForTheName;
}
i don't know what else to tell you...

syntax to update all fields in a table in one statement in sql

Can anyone suggest a Syntax to update all fields in a table in one statement.
I want to use it with prepared statement in jdbc.
can anyone suggest a example
Using a prepared statement is not that complicated:
PreparedStatement pstmt = connection.prepareStatement(
"UPDATE my_table SET column_1 = ?, column_2 = ?, column_3 = ?");
// assuming table has columns named as column_1,column_2,column_3 of type int,String,BigDecimal respectively
/* putting the values at runtime */
pstmt.setInt(1, 42); // use value 42 for column_1
pstmt.setString(2, "foo"); // use value 'foo' for column_2
pstmt.setBigDecimal(3, new BigDecimal("123.456")); // use 123.456 for column_3
pstmt.executeUpdate();
connection.commit();
Of course you will need to add error handling to this example.
More examples can be found in the Java Tutorial:
http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
UPDATE your_table_name SET field1 = 'value1', field2 = 'value2'
Note : I haven't specified WHERE clause, so these changes will be applied to every single row in a table.