Using SELECT .. AS in a Python Sqlite query - python-3.x

In SQLite3, I have a "Accounts" table. I can run any of these queries:
SELECT Last_Bal AS Balance FROM Accounts;
SELECT Last_Bal AS 'Balance' FROM Accounts;
SELECT Last_Bal as "Balance" FROM Accounts;
All three queries run fine, and display the word "Balance" as the column heading.
However, when I run this code in Python 3:
c.Execute( 'SELECT Last_Bal AS Balance FROM Accounts' )
I get the error message: "sqlite3.OperationalError: near "Balance": syntax error". If I try putting single quotes or double quotes around the word Balance, as in this:
c.Execute( 'SELECT Last_Bal AS "Balance" FROM Accounts' )
I get the error message: "_tkinter.TclError: Invalid column index Balance"
I've tried swapping the single quotes for double quotes, and even triple quotes, but nothing seems to work.
SOLVED: Stupid User Error - I was using two different SELECT statements trying to build a TreeView. Thanks for your help.

Related

ADF: Pass dynamic Where Clause as a string with quotes

I have a lookup that retrieves a few records from a SQL Server table containing server, database, schema, table name and a whole where clause. These values are passed to a copy data (within a ForEach) In the copy data i have tried to use two different Dynamic query statement, but I seem to get an error. And can't figure out where I'm going wrong.
Values in table:
SRC_SERVERNAME
SRC_DATABASE
SRC_SCHEMANAME
SRC_TABLENAME
SRC_WHERE_DATE_CLAUSE
SQ01
NAV
dbo
Company$Sales Invoice Header
where [Posting Date] >= '2021-01-01'
Source setup:
Error for statement 1:
A database operation failed with the following error: 'Incorrect syntax near '.'.'
Incorrect syntax near '.'., SqlErrorNumber=102,Class=15,State=1,
Error for statement 2:
A database operation failed with the following error: 'Incorrect syntax near '.'.'
Incorrect syntax near '.'., SqlErrorNumber=102,Class=15,State=1,
Statement 1 (query):
SELECT *
FROM #{item().SRC_SERVERNAME}.#{item().SRC_DATABASENAME}.#{item().SRC_SCHEMANAME}.#{item().SRC_TABLENAME},' ',#{item().SRC_WHERE_DATE_CLAUSE}
Statement 2 (dynamic query with concat):
#concat('select * from ',item().SRC_SERVERNAME,'.',item().SRC_DATABASENAME,'.',item().SRC_SCHEMANAME,'.',item().SRC_TABLENAME,' ',item().SRC_WHERE_DATE_CLAUSE)
There is a syntax error in your query.
In the 4-part naming of SQL database, server name/database name/schema name/table name should be separated by ‘.’.
When you have space or other special characters in the name of server/database/schema/table, they should be embedded inside square braces [].
#concat('select * from [',item().SRC_SERVERNAME, '].[',item().SRC_DATABASENAME,'].[',item().SRC_SCHEMANAME,'].[',item().SRC_TABLENAME, '] ',item().SRC_WHERE_DATE_CLAUSE)

REPLACE doesn't work for strings in BigQuery

I tried to use REPLACE to delete some words, like 'HOMEMAKER' and 'HOUSEWIFE', from strings. But I failed to change those words into empty space. Why is that happening?
I want to delete strings like 'HOMEMAKER' and 'HOUSEWIFE' from column EMPLOYER using REPLACE function but failed. I also tried REGEXP_REPLACE but failed again. These are the table I have (Sorry I want to build a table here but somehow it doesn't work).
EMPLOYER
RETIRED/HOMEMAKER
HOMEMAKER/HOMEMAKER
SELF-EMPLOYED/HOMEMAKER
We code is listed below:
SELECT EMPLOYER,
CASE WHEN EMPLOYER LIKE '%HOUSE%WIFE%'
THEN REGEXP_REPLACE(EMPLOYER,r'HOUSE%WIFE',' ')
WHEN EMPLOYER LIKE '%HOME%MAKER%'
THEN REGEXP_REPLACE(EMPLOYER, r'HOME%MAKER', ' ')
ELSE '0'
END AS SIGN
FROM fec.work
WHERE EMPLOYER LIKE '%HOME%MAKER%'
OR EMPLOYER LIKE '%HOUSE%WIFE%'
GROUP BY 1,2;
The result I want is like:
SIGN
RETIRED/
/
SELF-EMPLOYED/
But I got exactly the same columns in SIGN as EMPLOYER. Can anyone tell me why replace function did not make any changes?
You should use something like below
REGEXP_REPLACE(EMPLOYER, r'HOUSEWIFE|HOMEMAKER',' ')
you can use i flag to make this replacement case insensitive
REGEXP_REPLACE(EMPLOYER, r'(?i)HOUSEWIFE|HOMEMAKER',' ')
Either of these options should work for your case.
with test as (
select 'EMPLOYER' as my_str union all
select 'RETIRED/HOMEMAKER' as my_str union all
select 'HOMEMAKER/HOMEMAKER' as my_str union all
select 'SELF-EMPLOYED/HOMEMAKER' as my_str
)
select
my_str,
REPLACE(REPLACE(my_str, 'HOUSEWIFE', ' '), 'HOMEMAKER', ' ') as replaced_str,
REGEXP_REPLACE(my_str, r'HOUSEWIFE|HOMEMAKER', ' ') as regexed_str
from test

dbSendquery giving format error

I need to create a table and insert some values into it uisng r
library(sqldf)
Company_Master <- dbConnect(SQLite(), dbname="Company Master.sqlite" )
dbSendQuery(conn = Company_Master,
"CREATE TABLE Company Master(
Comp_name varchar
Address varchar)
")
Till here no error is given.But after this when i want to insert some value into the table
dbSendQuery(conn = Company_Master, "INSERT INTO COMPANY MASTER
VALUES('INFOSYS','abcLALA')")
I get error like
Error in result_create(conn#ptr, statement) : near "Master": syntax error
I found the format on https://www.r-bloggers.com/r-and-sqlite-part-1/ and don't seem to get any other format except if using dbCEATETABLE. What is wrong in this format? Please help

Condition IF In Power Query's Advanced Editor

I have a field named field, and I would like to see if it is null, but I get an error in the query, my code is this:
let
Condition= Excel.CurrentWorkbook(){[Name="test_table"]}[Content],
field= Condition{0}[fieldColumn],
query1="select * from students",
if field <> null then query1=query1 & " where id = '"& field &"',
exec= Oracle.Database("TESTING",[Query=query1])
in
exec
but I get an error in the condition, do you identify the mistake?
I got Expression.SyntaxError: Token Identifier expected.
You need to assign the if line to a variable. Each M line needs to start with an assignment:
let
Condition= Excel.CurrentWorkbook(){[Name="test_table"]}[Content],
field= Condition{0}[fieldColumn],
query1="select * from students",
query2 = if field <> null then query1 & " some stuff" else " some other stuff",
exec= Oracle.Database("TESTING",[Query=query2])
in
exec
In query2 you can build the select statement. I simplified it, because you also have conflicts with the double quotes.
I think you're looking for:
if Not IsNull(field) then ....
Some data types you may have to check using IsEmpty() or 'field is Not Nothing' too. Depending on the datatype and what you are using.
To troubleshoot, it's best to try to set a breakpoint and locate where the error is happening and watch the variable to prevent against that specific value.
To meet this requirement, I would build a fresh Query using the PQ UI to select the students table/view from Oracle, and then use the UI to Filter the [id] column on any value.
Then in the advanced editor I would edit the generated FilteredRows line using code from your Condition + field steps, e.g.
FilteredRows = Table.SelectRows(TESTING_students, each [id] = Excel.CurrentWorkbook(){[Name="test_table"]}{0}[fieldColumn])
This is a minor change from a generated script, rather than trying to write the whole thing from scratch.

Cognos - Promptmany with default selection 'ALL' not working

I have a report that uses SQL Query. I have a promptmany macro in the SQL:
#promptmany('countryParam', 'string', 'and 1=1' , 'and s.country in (', 'countryParam', ' )')#
This prompt has a default value and 1=1 which should be passed if no value is selected.
On the prompt page, I have the prompt which displays all the countries.
I want the prompt to show All at the top of the list of countries in the prompt box. When the user selects All , no value should be passed in the SQL.
I have tried static choice to use blank and display to use All, but it passes blank value in the sql.
where s.country in ('')
It works with the prompt macro but dosent work with promptmany.
Any suggestions?
Use Static choices. For one option, Display 'All' and use 'All'.
In your filter:
case ?prompt1?
when 'All' then ( 1 = 1 )
else ( [do something here] )
end
After trying a lot of options, I was able to manipulate the SQL. The below SQL works
and ( #prompt('IJParam', 'string', '1=1' , 's.ij_code=')#
or
#promptmany('IJParam', 'string', ' 1=1' , ' s.ij_code in (', 'IJParam', ' )')#
)

Resources