I am successfully adding a table to an sql lite database but I am struggling with the syntax to write values to the table, please take a look at the code below and advice me on the correct syntax.
Sorry Code!
var db = window.openDatabase("Database", "1.0", "GBA", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS vehiclecheck');
tx.executeSql('CREATE TABLE IF NOT EXISTS vehiclecheck (id INTEGER PRIMARY KEY AUTOINCREMENT, checkfield VARCHAR(12), class INTEGER)');
tx.executeSql('INSERT INTO vehiclecheck (checkfield, class) VALUES (' + 'Test' + ',' + 1 + ')');
Try this insertion
tx.executeSql("insert into vehiclecheck(checkfield, class) values(?,?)",["Test",'1']);
You need to escape Test. If you consider your SQL:
INSERT INTO vehiclecheck (checkfield, class) VALUES (Test,1)
You can see the single quotes around Test are missing.
Don't forget that you can use bound params as well. An example is here: http://www.raymondcamden.com/index.cfm/2011/10/20/Example-of-PhoneGaps-Database-Support
Related
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.
I am trying to create cache in Ignite using sql query
CacheConfiguration<?, ?> cacheCfg = new CacheConfiguration<>(DUMMY_CACHE_NAME);
IgniteCache<?, ?> cache = igniteInstance.getOrCreateCache(cacheCfg);
cache.query(new SqlFieldsQuery(
"CREATE TABLE IF NOT EXISTS MY_TABLE (id varchar, value varchar, PRIMARY KEY(id)) " +
"WITH \"template=replicated\", \"DATA_REGION=" + IgniteCacheConfiguration.DEFAULT_REGION + "\""));
Then I am trying to put some data into the cache using key-value api
IgniteCache<String, String> cache = ignite.cache("SQL_PUBLIC_MY_TABLE");
cache.put("1","example");
I know the data is stored successfully, I can retrieve it, I see that cache size is correct but when I am trying to retrieve the data with SQL
SELECT * FROM "PUBLIC".MY_TABLE
for example using DBeaver I am getting empty result
Do you know if it is how Ignite works or there is some additional configuration needed ?
By default, it wraps the kay and values in a class. You can tell it not to do that with the wrap_key and wrap_value parameter like this:
create table MY_TABLE (id varchar, value varchar, PRIMARY KEY(id)) with "wrap_key=false,wrap_value=false" ;
Let's say I have an associative array (defined in another language) like so:
apply = {
'qwer': ['tju', 'snf', 'rjtj', 'sadgg']
'asdf': ['rtj', 'sfm', 'rtjt', 'adjdj']
...
'zxcv': ['qwr', 'trj', '3w4u', '3tt3']
}
And I have a table like so:
CREATE TABLE apples (
id integer,
name varchar(10),
key varchar(10),
value varchar(10)
);
I want to apply an update where if apples.value is in one of the lists of the apply variable, then set the apples.key to the key of the array. If apples.value was tju then set apples.key to qwer.
My current approach looks like this (mixing PostgreSQL with any procedural language):
for key in apply.keys:
UPDATE apples SET key=$key
FROM (SELECT unnest(array($apply[key])) AS value) AS update_table
WHERE value=update_table.value
I want to do this in a single statement.
As proof of concept for the given example, with the string formatted exactly as you display:
Demonstrating a prepared statement, like your client probably uses.
PREPARE my_update AS
UPDATE apples a
SET key = upd.key
FROM (
SELECT trim (split_part(key_val, ': ', 1), ' ''') AS key
, string_to_array(translate(split_part(key_val, ': ', 2), '[]''', ''), ', ') AS val_arr
FROM unnest(string_to_array(trim($1, E'{}\n'), E'\n')) key_val
) upd
WHERE a.value = ANY(upd.val_arr);
EXECUTE in the same session any number of times:
EXECUTE my_update($assoc_arr${
'qwer': ['tju', 'snf', 'rjtj', 'sadgg']
'asdf': ['rtj', 'sfm', 'rtjt', 'adjdj']
'zxcv': ['qwr', 'trj', '3w4u', '3tt3']
}$assoc_arr$);
SQL Fiddle.
Related:
Insert text with single quotes in PostgreSQL
Split given string and prepare case statement
But I would rather process the type in its original language and pass key and val_arr separately.
I have a table which has a column that represents the name of a table we'd like to create. There's a foreign key relationship to another table which has a column representing the name of the columns for the desired table (all data types assumed to be nvarchar). I'm using a stored procedure to create this table. Essentially what I'm doing is getting all of the relevant data from my tables, then building a SQL string up to generate the table, and finally using EXEC sp_executesql #CreateTableSQL.
#CreateTableSQL is generated through string concatenation like this:
SET #CreateTableSQL = 'CREATE TABLE ' + #TableName + ' (' + #ColumnString + ')';
This leaves me vulnerable to SQL injection. If someone were to use a #TableName value of:
C (t int); DROP TABLE MyTable;--
then this would drop MyTable (undesirable).
Can someone help me build this SQL and leave it invulnerable to injection? Help is greatly appreciated. Thanks!
You can make use of QUOTENAME() function which will enforce square brackets [] around the variables(Table and column names) and any value passed to these variables will only be treated as an Object name.
Something like ......
SET #CreateTableSQL = 'CREATE TABLE ' + QUOTENAME(#TableName)
+ ' (' + QUOTENAME(#ColumnString) + ')';
Now even if someone passes a value of C (t int); DROP TABLE MyTable;-- to any of these variables, the whole value C (t int); DROP TABLE MyTable;-- will still be treated as an object name.
I want to declare a variable in SQLite and use it in insert operation.
Like in MS SQL:
declare #name as varchar(10)
set name = 'name'
select * from table where name = #name
For example, I will need to get last_insert_row and use it in insert.
I have found something about binding but I didn't really fully understood it.
SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.
I've used the below approach for large projects and works like a charm.
/* Create in-memory temp table for variables */
BEGIN;
PRAGMA temp_store = 2; /* 2 means use in-memory */
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);
/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');
/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';
/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...
DROP TABLE _Variables;
END;
For a read-only variable (that is, a constant value set once and used anywhere in the query), use a Common Table Expression (CTE).
WITH const AS (SELECT 'name' AS name, 10 AS more)
SELECT table.cost, (table.cost + const.more) AS newCost
FROM table, const
WHERE table.name = const.name
SQLite WITH clause
Herman's solution works, but it can be simplified because Sqlite allows to store any value type on any field.
Here is a simpler version that uses one Value field declared as TEXT to store any value:
CREATE TEMP TABLE IF NOT EXISTS Variables (Name TEXT PRIMARY KEY, Value TEXT);
INSERT OR REPLACE INTO Variables VALUES ('VarStr', 'Val1');
INSERT OR REPLACE INTO Variables VALUES ('VarInt', 123);
INSERT OR REPLACE INTO Variables VALUES ('VarBlob', x'12345678');
SELECT Value
FROM Variables
WHERE Name = 'VarStr'
UNION ALL
SELECT Value
FROM Variables
WHERE Name = 'VarInt'
UNION ALL
SELECT Value
FROM Variables
WHERE Name = 'VarBlob';
Herman's solution worked for me, but the ... had me mixed up for a bit. I'm including the demo I worked up based on his answer. The additional features in my answer include foreign key support, auto incrementing keys, and use of the last_insert_rowid() function to get the last auto generated key in a transaction.
My need for this information came up when I hit a transaction that required three foreign keys but I could only get the last one with last_insert_rowid().
PRAGMA foreign_keys = ON; -- sqlite foreign key support is off by default
PRAGMA temp_store = 2; -- store temp table in memory, not on disk
CREATE TABLE Foo(
Thing1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);
CREATE TABLE Bar(
Thing2 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
FOREIGN KEY(Thing2) REFERENCES Foo(Thing1)
);
BEGIN TRANSACTION;
CREATE TEMP TABLE _Variables(Key TEXT, Value INTEGER);
INSERT INTO Foo(Thing1)
VALUES(2);
INSERT INTO _Variables(Key, Value)
VALUES('FooThing', last_insert_rowid());
INSERT INTO Bar(Thing2)
VALUES((SELECT Value FROM _Variables WHERE Key = 'FooThing'));
DROP TABLE _Variables;
END TRANSACTION;
To use the one from denverCR in your example:
WITH tblCTE AS (SELECT "Joe" AS namevar)
SELECT * FROM table, tblCTE
WHERE name = namevar
As a beginner I found other answers too difficult to understand, hope this works
Creating "VARIABLE" for use in SQLite SELECT (and some other) statements
CREATE TEMP TABLE IF NOT EXISTS variable AS SELECT '2002' AS _year; --creating the "variable" named "_year" with value "2002"
UPDATE variable SET _year = '2021'; --changing the variable named "_year" assigning "new" value "2021"
SELECT _year FROM variable; --viewing the variable
SELECT 'TEST', (SELECT _year FROM variable) AS _year; --using the variable
SELECT taxyr FROM owndat WHERE taxyr = (SELECT _year FROM variable); --another example of using the variable
SELECT DISTINCT taxyr FROM owndat WHERE taxyr IN ('2022',(SELECT _year FROM variable)); --another example of using the variable
DROP TABLE IF EXISTS variable; --releasing the "variable" if needed to be released
After reading all the answers I prefer something like this:
select *
from table, (select 'name' as name) const
where table.name = const.name
Try using Binding Values. You cannot use variables as you do in T-SQL but you can use "parameters". I hope the following link is usefull.Binding Values
I found one solution for assign variables to COLUMN or TABLE:
conn = sqlite3.connect('database.db')
cursor=conn.cursor()
z="Cash_payers" # bring results from Table 1 , Column: Customers and COLUMN
# which are pays cash
sorgu_y= Customers #Column name
query1="SELECT * FROM Table_1 WHERE " +sorgu_y+ " LIKE ? "
print (query1)
query=(query1)
cursor.execute(query,(z,))
Don't forget input one space between the WHERE and double quotes
and between the double quotes and LIKE