Python 3 variable that contains questionmarks - sqlite

I'm trying to make a python3 sqlite3 database function that determines the amount of column with a for loop. During this for loop I want to add a "?" to a variable for each column.
So what I'm trying to do now is create a list from which I remove the quotes and brackets afterwards but using the .strip() and .replace() method don't seem to work for me either.
lijst = []
lijst.append("?")
lijst.append("?")
lijst.replace('"', '')
lijst.strip([])
print(lijst)
In the end I want it to look a bit like this (?, ?, ?).

lijst is a list, not a string. You can't treat the two interchangeably. Instead, you can construct a string directly. Where n in the number of ? you want in your final string:
n = 3
result = "({})".format(", ".join("?"*n))
print(result)
# (?, ?, ?)

Related

Find all records by the value of the json key in MariaDB 10.1

I have MariaDB 10.1. - I can't use JSON functions - JSON_EXTRACT etc.).
In the database I have a table CONTRACTS and a column data, which contains JSON (data type TEXT):
{"879": "Test", "880": "15255", "881": "2021-10-22"}
And I need to find all records that have a key value of "880" in some range, eg greater than 10000 and less than 20000, ie. in this case, a record with a value of 15255.
Thanks for advice.
Maybe something like this:
SELECT
TRIM(BOTH '"' FROM
REGEXP_SUBSTR(REGEXP_SUBSTR(CONTRACTS.`data`, '"880": "[0-9]+"'), '"[0-9]+"$')
) * 1 BETWEEN 10000 AND 20000
FROM
(SELECT
'{"879": "Test", "880": "15255", "881": "2021-10-22"}' AS `data`
) AS CONTRACTS
So the most internal regexp gives you the key + value. The outer regexp takes that result and extracts the value in quotes. Trim the quotes and test the value. You could use the entire TRIM(...) as a criterium .

Passing multiple parameters to an SQLite query in Racket

I'm trying to pass more than one variable to an sqlite query in Racket.
(define select-test
(prepare dbconn "SELECT count(*) FROM All_data WHERE Season = ? AND Division = '?'"))
(define season 2019)
(define league "E0")
;(query-value dbconn select-test '(season league))
;(query-value dbconn select-test season league)
There are examples online showing both a list and separate variables as input to a query, but neither of these are working for me.
I either get this message for the list:
query-value: cannot convert given value to SQL type
given: '(season league)
type: parameter
dialect: SQLite
or 'wrong number of parameters for query' if done separately.
Can someone please help with the correct syntax?
The problem is in your SQL. This statement:
SELECT count(*) FROM All_data WHERE Season = ? AND Division = '?'
has one parameter (for the Season comparison). The '?' is just a literal string containing a question mark. Just write ? instead, like this:
SELECT count(*) FROM All_data WHERE Season = ? AND Division = ?
Then call it with two arguments, like this:
(query-value dbconn select-test season league)
By the way, you can double-check the number of parameters the prepared statement has with
(length (prepared-statement-parameter-types select-test))
With SQLite, there isn't any information in the types themselves, but the length tells you the number of parameters.

Using InStr in Access VBA to lookup a string value from another table

Very new to access VBA and would love some guidance on this.
I am searching through a string and looking for a particular substring in this field. This substring would have a value based on another table, ie
order = "Reference order QQ131415"
The problem is, there is no particular pattern for order numbers. Some are 7 digits, some are 10 and some have dashes in there.
There is a table i have access too that has these order numbers though, and I guess I am trying to use that table as a dictionary.
my very very basic Access VBA code is like this
' order= Instr(1, rst![order], qst![order_id],vbBinaryCompare)'
order is the string where i have the order id i am trying to extract
order_id is the actual id from a seperate table.
Is this something that Access VBA can handle?
So i think this will help you
You're not very clear in the sentence following on from "order=" with your code. Could you clear that up.
Instr(string1, String2, [ compare ])
string1 Required. String expression being searched.
string2 Required. String expression sought.
Instr returns a Variant (number in this case) specifying the position of the first occurrence of one string within another. So it should be:
Position= InStr(1, string1, string2, 1)
So you'd now know that the ordernumber starts at position x in Order. You'd then have to do a left(Order, Len(order) -x) to extract the string.
Youd do that in a nested loop because youll have to loop through your dictionary per record in Order.
E.g.
Dim rsOrder as DAO.recordset
Dim rsOrderId as Dao.recordset
dim orderTest as integer
dim stringcapture as string
Set rsOrder = Currentdb.OpenRecordset("[SELECT STRING]")
rsOrder.Movefirst
Do until rsOrder.EOF or rsOrder.BOF
Order = rsOrder![OrderFieldName]
Set rsOrderId = Currentdb.OpenRecordSet("[SELECT STRING]")
rsOrderID.Movefirst
Do Until rsOrderID.EOF or rsOrderID.BOF
OrderID = rsOrderID![OrderIDFieldName]
orderTest = Instr(1, Order, OrderID,1)
StringCapture = left(Order, Len(order) -OrderTest)
rsOrderID.movenext
Loop
rsOrder.movenext
Loop
rsOrder.close
rsOrderID.close
Something to that affect.

"Row value misused" error in SQLite database

I'm getting an error from an sqlite3 query for which I can't find any reference material. Googling the string takes me deep in the SQLite code itself, and that's so opaque I can't make heads or tails of it.
The table schema:
CREATE TABLE quote (
seqnum INTEGER,
session STRING,
timestamp_sip INTEGER,
timestamp_1 INTEGER,
market_center STRING,
symbol STRING,
bid_price INTEGER,
bid_lots INTEGER,
offer_price INTEGER,
offer_lots INTEGER,
flags INTEGER,
PRIMARY KEY (symbol, seqnum) );
The query:
select (seqnum, session, timestamp_sip, timestamp_1, market_center, symbol)
from quote
where symbol = 'QQQ';
The error:
Error: row value misused
I have no idea how to proceed here. There is plenty of data in the table that would match the query:
sqlite> select count(*) from quote where symbol = 'QQQ';
2675931
Can anyone offer any guidance here? Sqlite version is 3.16.2.
Nevermind. Those parentheses around the select columns (left over from a copy/paste) are the problem. Poor error message, maybe. But my fault.
I had a similar when working with a Rails 5.2 Application.
For my case I was trying to write a search query for a model in application:
def self.search(params)
applications = all.order('created_at DESC') # for not existing params args
applications = applications.where("cast(id as text) like ?, email like ?, first_name like ?, last_name like ?, appref like ?", "#{params[:search]}", "%#{params[:search]}%", "#{params[:search]}", "#{params[:search]}", "#{params[:search]}",) if params[:search]
applications
end
The issue was that I was using a comma (,) to separate the search parameters, I simply corrected by using an OR instead:
def self.search(params)
applications = all.order('created_at DESC') # for not existing params args
applications = applications.where("cast(id as text) like ? OR email like ? OR first_name like ? OR last_name like ? OR appref like ?", "#{params[:search]}", "%#{params[:search]}%", "#{params[:search]}", "#{params[:search]}", "#{params[:search]}",) if params[:search]
applications
end
I deleted brackets from query and it work for me: from SELECT (column1, column2, ...) FROM table to SELECT column1, column2, ... FROM table
JUST
select seqnum, session, timestamp_sip, timestamp_1, market_center, symbol
from quote
where symbol = 'QQQ';
then it works.
Yeah, this bug is happing in my code, and I found this questions, but none of the answers helped me.
I fixed this problem with remove the same column in my SELECT command.
(It's stupid, because I can't select the column if the column is already in the condition subcommand.)
This is the problem SQL command (DO NOT USE THIS):
SELECT (`id`, `username`) FROM `users` WHERE `id` = 'someone_s id'
This is the fixed SQL command (PLEASE USE THIS):
SELECT (`username`) FROM `users` WHERE `id` = 'someone_s id'
The same error occurs when putting the elements of a GROUP BY clause inside brackets, as in
SELECT 1 as a, 2 as b FROM (SELECT 1) GROUP BY (a, b);
The correct syntax is, of course
SELECT 1 as a, 2 as b FROM (SELECT 1) GROUP BY a, b;

SQLite strings filtering

for example my "select" query returns rows:
"asd/1"
"asd/2"
but for me rows "asd/1", "asd/2" represents the same value. Is any way to truncate strings to such result: (i want to truncate everything after '/' inclusive)
"asd"
??
Something like this should work
select distinct substr(column_name, 1, instr(column_name, '/') - 1) from table_name
This get back column_name up to the first '/' in the string (but not including the slash because of the -1) and then only give back the unique results (because of the distinct keyword)

Resources