Im trying to retrieve the latest versions of audit questions stored in table T3 of the hs_audit.sqlite. I have tried multiple versions of the cur.exectute line but keep getting a result = None. I'm new to sqlite so can anyone help me with the correct syntax.
If I execute the cur.execute line as follows
cur.execute("SELECT hvq1 FROM T3 WHERE audit_ver = 1")
and remove
con.text_factory = str
it works so i think the problem must be the use of variables in the sqlite command.
max_audit_ver = 1
audit_questions = ["hvq1", "hvq2", "hvq3", "hvq4", "hvq5"]
count = 0
for quest in audit_questions:
con = sqlite3.connect("hs_audit.sqlite")
con.text_factory = str
cur = con.cursor()
cur.execute("SELECT '%s' FROM T3 WHERE audit_ver = '%s'" % (quest, max_audit_version))
result = cur.fetchone()
con.close()
print "Question =%s" % (quest)
print "Audit Version =%s" % (max_audit_version)
print "The Count Is =%s" % (count)
print "The return from the DB is =%s" % (result)
count += 1
Mind the synthax... max_audit_version and max_audit_ver
On the other hand, you should read this page, you will find some important note such as :
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
Related
I have a tasks application with two tables. One table has the task name, date, owner etc and the other has the comments for the task linked to the task number so there can be multiple comments attached to a single task.
Both tables have FTS5 indexes. Within my app I want to search both tables for a word and present the rows to the user. I have the below working for each table individually but how do I construct a query that returns data from both FTS5 tables?
(python3.6)
c.execute("select * from task_list where task_list = ? ", [new_search])
c.execute("select * from comments where comments = ? ", [new_search])
thanks #tomalak never thought of doing that, was focused on the query. Here's what I came up with and works for my purposes. Probably better ways to achieve the same result but I'm a beginner. This is a Tkinter app.
def db_search():
rows = ''
conn = sqlite3.connect('task_list_database.db')
c = conn.cursor()
d = conn.cursor()
new_search = entry7.get()
c.execute("select * from task_list where task_list = ? ", [new_search])
d.execute("select * from comments where comments = ? ", [new_search])
rows1 = c.fetchall()
rows2 = d.fetchall()
rows = rows1 + rows2
clear_tree(tree)
for row in rows:
tree.insert("", END, values=row)
conn.close()
I want to insert a Dataframe in a table using ODBC.jl , the table already exists and it seems that i can't use the function ODBC.load with it (even with the append=true).
usually i insert DataFrames with copyIn by loading the dataframe as a csv but with just ODBC it seems i can't do that .
The last thing i found is :
stmt = ODBC.prepare(dsn, "INSERT INTO cool_table VALUES(?, ?, ?)")
for row = 1:size(df, 1)
ODBC.execute!(stmt, [df[row, x] for x = 1:size(df, 2)])
end
but this is line by line , it's incredibly long to insert everything .
I tried also to do it myself like this :
_prepare_field(x::Any) = x
_prepare_field(x::Missing) = ""
_prepare_field(x::AbstractString) = string(''', x, ''')
row_names = join(string.(Tables.columnnames(table)), ",")
row_strings = imap(Tables.eachrow(table)) do row
join((_prepare_field(x) for x in row), ",") * "\n"
end
query = "INSERT INTO $tableName($row_names) VALUES $row_strings"
#debug "Inserting $(nrow(df)) in $tableName)"
DBInterface.execute(db.conn, query)
but it throw me an error because of some "," not at the right place at like col 9232123
which i can't find because i have too many lines , i guess it's the _prepare_field that doesn't cover all possible strings escape but i can't find another way .
Did i miss something and there is a easier way to do it ?
Thank you
I have a model in excel and trying to feed inputs through ASP.NET to the excel and returning the back the model results over the grid in the front end. I'm using EPPlus package in ASP.NET as it doesn't need MS Office to be installed.
I have trouble getting the value of the cell where NPV [Net Present Value] and IRR [Internal rate of return] functions have been used. It always returns #VALUE or #NAME. As a workaround, I was able to calculate NPV manually but I'm having a tough time with IRR.
Is there a way in EPPlus to paste all the cells as values in the worksheet?
Or is there any other alternative?
Please help and thanks in advance
Update : I have EPPlus 4.5.3.1 and Visual studio 2013.
string strfilepath = Server.MapPath(destPath);
FileInfo fileInfo = new FileInfo(strfilepath);
ExcelPackage p = new ExcelPackage(fileInfo);
ExcelWorksheet myWorksheet = p.Workbook.Worksheets["Financial"];
GridView1.Rows[0].Cells[2].Text = float.Parse(myWorksheet1.Cells["f57"].Value.ToString()).ToString("N2");
I have tried all possible ways in EPPlus but I was not able to calculate IRR. I came up with a solution in SQL and it gives the result close to excel 's IRR function.
CREATE FUNCTION [dbo].[Ufn_irr1] (#strIDs1 VARCHAR(10),
#strIDs2 VARCHAR(10),
#guess DECIMAL(30, 10))
returns DECIMAL(30, 10)
AS
BEGIN
DECLARE #t_IDs TABLE
( a
id INT IDENTITY(0, 1),
value DECIMAL(30, 10)
)
DECLARE #strIDs VARCHAR(max)
SET #strIDs = #strIDs1 + ',' + #strIDs2
DECLARE #strID VARCHAR(12),
#sepPos INT,
#NPV DECIMAL(30, 10)
SET #strIDs = COALESCE(#strIDs + ',', '')
SET #sepPos = Charindex(',', #strIDs)
WHILE #sepPos > 0
BEGIN
SET #strID = LEFT(#strIDs, #sepPos - 1)
INSERT INTO #t_IDs
(value)
SELECT ( Cast(#strID AS DECIMAL(20, 10)) )
WHERE Isnumeric(#strID) = 1
SET #strIDs = RIGHT(#strIDs, Datalength(#strIDs) - #sepPos)
SET #sepPos = Charindex(',', #strIDs)
END
SET #guess = CASE
WHEN Isnull(#guess, 0) <= 0 THEN 0.00001
ELSE #guess
END
SELECT #NPV = Sum(value / Power(1 + #guess, id))
FROM #t_IDs
WHILE #NPV > 0
BEGIN
SET #guess = #guess + 0.00001
SELECT #NPV = Sum(value / Power(1 + #guess, id))
FROM #t_IDs
END
RETURN #guess
END
I am just starting to work with openedge and I need to join information from two tables but I just need the first row from the second one.
Basically I need to do a typical SQL Cross Apply but in progress. I look in the documentation and the Statement FETCH FIRST 10 ROWS ONLY only in OpenEdge 11.
My query is:
SELECT * FROM la_of PUB.la_ofart ON la_of.empr_cod = la_ofart.empr_cod
AND la_of.Cod_Ordf = la_ofart.Cod_Ordf
AND la_of.Num_ordex = la_ofart.Num_ordex AND la_of.Num_partida = la_ofart.Num_partida
CROSS APPLY (
SELECT TOP 1 ofart.Cod_Ordf AS Cod_Ordf_ofart ,
ofart.Num_ordex AS Num_ordex_ofart
FROM la_ofart AS ofart
WHERE ofart.empr_cod = la_ofart.empr_cod
AND ofart.Num_partida = la_ofart.Num_partida
AND la_ofart.doc1_num = ofart.doc1_num
AND la_ofart.doc2_linha = ofart.doc2_linha
ORDER BY ofart.Cod_Ordf DESC) ofart
I am using SSMS to extract data from OE10 using an ODBC connector and querying to OE using OpenQuery.
Thanks for all help.
If I correctly understood your question, maybe you can use something like this. Maybe this isn't the best solution for your problem, but may suit your needs.
DEF BUFFER ofart FOR la_ofart.
DEF TEMP-TABLE tt-ofart NO-UNDO LIKE ofart
FIELD seq AS INT
INDEX ch-seq
seq.
DEF VAR i-count AS INT NO-UNDO.
EMPTY TEMP-TABLE tt-ofart.
blk:
FOR EACH la_ofart NO-LOCK,
EACH la_of NO-LOCK
WHERE la_of.empr_cod = la_ofart.empr_cod
AND la_of.Cod_Ordf = la_ofart.Cod_Ordf
AND la_of.Num_ordex = la_ofart.Num_ordex
AND la_of.Num_partida = la_ofart.Num_partida,
EACH ofart NO-LOCK
WHERE ofart.empr_cod = la_ofart.empr_cod
AND ofart.Num_partida = la_ofart.Num_partida
AND ofart.doc1_num = la_ofart.doc1_num
AND ofart.doc2_linha = la_ofart.doc2_linha
BREAK BY ofart.Cod_Ordf DESCENDING:
ASSIGN i-count = i-count + 1.
CREATE tt-ofart.
BUFFER-COPY ofart TO tt-ofart
ASSIGN ofart.seq = i-count.
IF i-count >= 10 THEN
LEAVE blk.
END.
FOR EACH tt-ofart USE-INDEX seq:
DISP tt-ofart WITH SCROLLABLE 1 COL 1 DOWN NO-ERROR.
END.
How can I get a single row result (e.g. in form of a table/array) back from a sql statement. Using Lua Sqlite (LuaSQLite3). For example this one:
SELECT * FROM sqlite_master WHERE name ='myTable';
So far I note:
using "nrows"/"rows" it gives an iterator back
using "exec" it doesn't seem to give a result back(?)
Specific questions are then:
Q1 - How to get a single row (say first row) result back?
Q2 - How to get row count? (e.g. num_rows_returned = db:XXXX(sql))
In order to get a single row use the db:first_row method. Like so.
row = db:first_row("SELECT `id` FROM `table`")
print(row.id)
In order to get the row count use the SQL COUNT statement. Like so.
row = db:first_row("SELECT COUNT(`id`) AS count FROM `table`")
print(row.count)
EDIT: Ah, sorry for that. Here are some methods that should work.
You can also use db:nrows. Like so.
rows = db:nrows("SELECT `id` FROM `table`")
row = rows[1]
print(row.id)
We can also modify this to get the number of rows.
rows = db:nrows("SELECT COUNT(`id`) AS count FROM `table`")
row = rows[1]
print(row.count)
Here is a demo of getting the returned count:
> require "lsqlite3"
> db = sqlite3.open":memory:"
> db:exec "create table foo (x,y,z);"
> for x in db:urows "select count(*) from foo" do print(x) end
0
> db:exec "insert into foo values (10,11,12);"
> for x in db:urows "select count(*) from foo" do print(x) end
1
>
Just loop over the iterator you get back from the rows or whichever function you use. Except you put a break at the end, so you only iterate once.
Getting the count is all about using SQL. You compute it with the SELECT statement:
SELECT count(*) FROM ...
This will return one row containing a single value: the number of rows in the query.
This is similar to what I'm using in my project and works well for me.
local query = "SELECT content FROM playerData WHERE name = 'myTable' LIMIT 1"
local queryResultTable = {}
local queryFunction = function(userData, numberOfColumns, columnValues, columnTitles)
for i = 1, numberOfColumns do
queryResultTable[columnTitles[i]] = columnValues[i]
end
end
db:exec(query, queryFunction)
for k,v in pairs(queryResultTable) do
print(k,v)
end
You can even concatenate values into the query to place inside a generic method/function.
local query = "SELECT * FROM ZQuestionTable WHERE ConceptNumber = "..conceptNumber.." AND QuestionNumber = "..questionNumber.." LIMIT 1"