Passing python list in hive query as parameters - hive

from tkinter import *
import pyodbc
with pyodbc.connect("DSN=ffff", autocommit=True) as conn:
df2 = pd.read_sql("SELECT * FROM holdingsummarysaaas", conn)
list46 = []
for md in df2['clientcode']:
list46.append(md)
print(list46)
result = []
for i in list46:
if i not in result:
result.append(i)
print(result)
#list_no_nan = [x for x in result if pd.notnull(x)]
#print(list_no_nan)
#select name from studens where id in (%s)" % ",".join(map(str,mylist)
#def fun():
num1 = Entry(root)
blank = Entry(root)
Ans = (num1.get())
blank.insert(0, Ans)
if Ans in result:
df2 = pd.read_sql('SELECT * FROM holdingsummary where ' + ' or '.join(('clientcode = '
+ str(n) for n in result)),conn)
#df2 = pd.read_sql("SELECT * FROM holdingsummary where clientcode = '" + Ans + "'",
conn)
print(df2)
I am taking unique clientcodes from database and I want user input which is in fun
function should access the results list(unique clientcode )check each clientcode from list
and check whether entered clientcode if same in result list then open that clientcode.
for eg:
Ans=='100014'
#df2 = pd.read_sql("SELECT * FROM holdingsummarysaaas where clientcode = '100014', conn)

Related

How to store the first N rows of the current record as an array vector?

I defined a table as follows:
syms = "A"
datetimes = 2021.01.01..2022.01.01
n = 200
t = table(take(datetimes,n) as trade_time, take(syms,n) as sym,take(500+rand(10.0,n), n) as price)
You can try the following script:
syms = "A"
datetimes = 2021.01.01..2022.01.01
n = 200
t = table(take(datetimes,n) as trade_time, take(syms,n) as sym,take(500+rand(10.0,n), n) as price)
dayNum = 3
tbName = "t"
def getLastNDay(tbName, dayNum){
colName = "price"
scripts = "update " + tbName + " set lastNPrice = fixedLengthArrayVector("
for(n in 1..(dayNum-1)){
scripts = scripts + "move(" + colName + "," + n + "),"
}
scripts = scripts +"move(" + colName + "," + dayNum + "))"
print(scripts)
runScript(scripts)
}
getLastNDay(tbName, dayNum)
Output:

Select data from MySQL database and put in R dataframe

I can access a MySQL database and store output to an R dataframe using the following script where sam_pn = walker
con <- dbConnect(MySQL(),
user = user,
password = password,
host = host,
dbname = dbname)
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = 'walker'")
But what i would like to do is store 'walker' as an R value pn and then use pn value in the sql query like below so i can vary the pn value.... but it does not work. The syntax is not right. Note sam and che are tables in the database
pn = 'walker'
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = 'pn'")
pn = 'walker'
df = dbGetQuery(con, "SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = ?",
params = list(pn))
This is what worked in the end
pn = 'walker'
data = dbGetQuery(con, paste0("SELECT *
FROM sam AS s
JOIN che AS c ON c.che_label = s.sam_label1
WHERE sam_pn = '", pn ,"'"))

show sql data from User input

The code below inserts whatever data is typed into the text fields: name1 and phone1 into my database and I need to be able to type in stored data and retrieve it
def insert():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute('INSERT INTO people(name, phone) VALUES(?,?)',(name1, phone1,))
db.close()
but=Button(root,padx=2,pady=2,text='Submit',command=insert,font=('none 13 bold'))
but.place(x=60,y=100)
I need to retrieve the records by typing them into the same text field and then print them out. So far I have this but Im confused with the SQL.
def show():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute('SELECT * FROM people(name, phone) VALUES(?,?)',(name1, phone1,))
for row in cursor.fetchall():
print(row)
res=Button(root,padx=2,pady=2,text='Show',command=show,font=('none 13 bold'))
res.place(x=160,y=100)
Use:
cursor.execute('''INSERT INTO students(name, phone) VALUES(?,?)''',[(name1), (phone1)])
and:
cursor.execute("SELECT * FROM students WHERE name = ? AND phone = ?", [(name1),(phone1)])
Newcode:
def insert():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute('''INSERT INTO students(name, phone) VALUES(?,?)''',[(name1), (phone1)])
db.close()
def show():
name1 = textin.get()
phone1 = textinn.get()
conn = sqlite3.connect('D:\lastfm-dataset-360K\msd.sqlite3')
with conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM students WHERE name = ? AND phone = ?", [(name1),(phone1)])
for row in cursor.fetchall():
print(row)
res=Button(root,padx=2,pady=2,text='Show',command=show,font=('none 13 bold'))
res.place(x=160,y=100)

Python 3.4: Loop and Append: Why Not Working With cx_Oracle and Pandas?

For some reason, the following code only returns a dataframe of 10 rows instead of 20 (there are millions of rows in the SQL view).
When I viewed the output from print(data2), it showed the first 10 rows as a DataFrame, but the next DataFrame was empty.
import cx_Oracle as cx
import pandas as pd
conn = cx.Connection("username/pwd#server")
data = pd.DataFrame([])
SQL1 = '''SELECT * FROM TABLE_MV where rownum between '''
for i in range(1, 20, 10):
lower = i
upper = i+9
SQL3 = SQL1 + str(lower) + ' and ' + str(upper)
data2 = pd.read_sql(SQL3, conn)
print(data2)
data = data.append(data2)

wxPython; passing a value to wx.TextCtrl from another class

I'd like to thank everyone in advance for taking the time to review this question and I'm sure a lot of people get hung up on this at first and I am also a bit new to OOP, I've primarily done vbscripts in the past, so this is a new frontier to me.
My problem is that I need to:
pass a value from one panel to another...
I'm sure its something simple, but my hair is getting grey over this one.
import wx
import win32com.client
class FinanceInfo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
zbox = wx.BoxSizer(wx.VERTICAL)
self.Description = wx.TextCtrl(self, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(200,204))
zbox.Add(self.Description,0, wx.EXPAND,15)
self.SetSizer(zbox)
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
panel = wx.Panel(self, -1)
box1 = wx.BoxSizer(wx.HORIZONTAL)
box2 = wx.BoxSizer(wx.HORIZONTAL)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box4 = wx.BoxSizer(wx.HORIZONTAL)
box5 = wx.BoxSizer(wx.HORIZONTAL)
all_box = wx.BoxSizer(wx.VERTICAL)
overall = wx.BoxSizer(wx.HORIZONTAL)
nb = wx.Notebook(panel)
page2 = FinanceInfo(nb)
nb.AddPage(page2, "Finance Information")
first = wx.StaticText(panel, label="First Name: ")
last = wx.StaticText(panel, label="Last Name: ")
self.DATA = wx.ListBox(panel, style=wx.LB_SINGLE, size=(100,100))
self.Bind(wx.EVT_LISTBOX, self.OnSelection, id=self.DATA.GetId())
self.CLYa = wx.StaticText(panel, label="")
self.P2Da = wx.StaticText(panel, label="")
self.PLYa = wx.StaticText(panel, label="")
self.FN = wx.TextCtrl(panel, size=(75,-1))
self.LN = wx.TextCtrl(panel, size=(75,-1))
Search = wx.Button(panel, label="Search Patient")
self.Bind(wx.EVT_BUTTON, self.pulldata, id=Search.GetId())
Close = wx.Button(panel, label="Close Viewer")
self.Bind(wx.EVT_BUTTON, self.OnClose, id=Close.GetId())
box1.Add(first, 0, wx.ALL, 5)
box2.Add(last, 0, wx.ALL, 5)
box1.Add(self.FN, 1, wx.ALL, 5)
box2.Add(self.LN, 1, wx.ALL, 5)
box3.Add(self.DATA, 1 , wx.ALL, 5)
box4.Add(Search, 0, wx.ALL, 5)
box5.Add(Close, 0, wx.ALL, 5)
all_box.Add(box1, 0, wx.LEFT)
all_box.Add(box2, 0, wx.LEFT)
all_box.Add(wx.StaticLine(panel), 0, wx.ALL|wx.EXPAND, 5)
all_box.Add(box3, 0, wx.CENTER)
all_box.Add(box4, 0, wx.CENTER)
all_box.Add(box5, 0, wx.CENTER)
overall.Add(all_box,0,wx.EXPAND)
overall.Add(nb, 1, wx.EXPAND)
panel.SetSizer(overall)
self.SetSize((500, 275))
self.SetTitle("Maxident Historical Data Viewer")
self.Centre()
self.Show(True)
def OnClose(self, event):
quit()
def pulldata(self, event):
firstname = str(self.FN.GetValue())
lastname = str(self.LN.GetValue())
access = pullID(lastname.strip(), firstname.strip())
access.MoveFirst
dat = ""
while not access.EOF:
a = str(access.Fields("First Name").value)
b = str(access.Fields("Last Name").value)
PID = str(access.Fields("Patient Number").value)
name = str(a + " " + b + " :" + PID)
self.DATA.Insert(name, 0)
access.MoveNext()
def OnSelection(self, event):
x = str(self.DATA.GetStringSelection())
y = x.split(":")
PID = y[1]
pullfinancedata(PID)
def pullID(lastname, firstname):
DB = r"C:\Converted DBases\DATA.mdb"
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase(DB)
sql = "select [Patient Number], [First Name], [Last Name] from [tPatients] where [Last Name]='" + lastname.upper() + "' and [First Name]='" + firstname.upper() + "'"
access = db.OpenRecordset(sql)
return access
def pullfinancedata(PID):
DB = r"C:\Converted DBases\DATA.mdb"
engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase(DB)
sql = "select * from [tPayment History] where [Patient Number]=" + PID
access = db.OpenRecordset(sql)
dat = ""
while not access.EOF:
PD = "Payment Date:\t" + str(access.Fields("Payment Date").value) + '\n'
PM = "Payment Method:\t" + str(access.Fields("Payment Method").value) + '\n'
PP = "Patient Payment:\t" + str(access.Fields("Patient Payment").value) + '\n'
IP = "Insurance Payment:\t" + str(access.Fields("Insurance Payment").value) + '\n'
dat = dat + PD + PM + PP + IP + "\n ------------------ \n"
access.MoveNext()
"""
THIS IS WHERE I NEED HELP!
"""
print dat
"""
I need this dat variable to be passed to the FinanceInfo class and
i've tried FinanceInfo.Description.SetValue(dat) but its not working
"""
def main():
ex = wx.App()
Frame(None)
ex.MainLoop()
if __name__ == '__main__':
main()
I would also be grateful for any other tips or tricks. Not sure if my BoxSizer's make any sense, I mostly got the examples around other places.
There are several ways to do this:
Keep a reference to each panel and pass them around willy nilly. Then you can do stuff like self.panelOne.MyTextCtrl.SetValue(self.otherText.GetValue())
Use wx.PostEvent to pass around the information
Use pubsub
There are probably other ways too, but I prefer the last one for this sort of thing. You can read a simple example here: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/
The answer from Mike is correct. For simple communication between a few classes I however prefer to just send a reference to the other class. It is a clean/transparent method that doesnt needs any additional library. See here an example
I hope you already solved ... but if not I revised your example using pubsub and adodbapi.
I used my mdb and adodbapi becouse logic using OpendDataBase and .movenext not works in my Python 2.7 installation .
enter code here
import wx
from wx.lib.pubsub import Publisher
import win32com.client
import adodbapi
adodbapi.adodbapi.verbose = True
# adds details to the sample printout
class FinanceInfo(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
Publisher().subscribe(self.showFrame, ("show.mainframe"))
zbox = wx.BoxSizer(wx.VERTICAL)
self.Description = wx.TextCtrl(self, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(200,204))
zbox.Add(self.Description,0, wx.EXPAND,15)
self.SetSizer(zbox)
def showFrame(self, msg):
"""
Shows the frame and shows the message sent in the
text control
"""
self.Description.SetValue(msg.data)
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
#self.FinancePanelInfo = FinanceInfo(self)
panel = wx.Panel(self, -1)
box1 = wx.BoxSizer(wx.HORIZONTAL)
box2 = wx.BoxSizer(wx.HORIZONTAL)
box3 = wx.BoxSizer(wx.HORIZONTAL)
box4 = wx.BoxSizer(wx.HORIZONTAL)
box5 = wx.BoxSizer(wx.HORIZONTAL)
all_box = wx.BoxSizer(wx.VERTICAL)
overall = wx.BoxSizer(wx.HORIZONTAL)
nb = wx.Notebook(panel)
page2 = FinanceInfo(nb)
nb.AddPage(page2, "Finance Information")
first = wx.StaticText(panel, label="First Name: ")
last = wx.StaticText(panel, label="Last Name: ")
self.DATA = wx.ListBox(panel, style=wx.LB_SINGLE, size=(100,100))
self.Bind(wx.EVT_LISTBOX, self.OnSelection, id=self.DATA.GetId())
self.CLYa = wx.StaticText(panel, label="")
self.P2Da = wx.StaticText(panel, label="")
self.PLYa = wx.StaticText(panel, label="")
self.FN = wx.TextCtrl(panel, size=(75,-1))
self.LN = wx.TextCtrl(panel, size=(75,-1))
Search = wx.Button(panel, label="Search Patient")
self.Bind(wx.EVT_BUTTON, self.pulldata, id=Search.GetId())
Close = wx.Button(panel, label="Close Viewer")
self.Bind(wx.EVT_BUTTON, self.OnClose, id=Close.GetId())
box1.Add(first, 0, wx.ALL, 5)
box2.Add(last, 0, wx.ALL, 5)
box1.Add(self.FN, 1, wx.ALL, 5)
box2.Add(self.LN, 1, wx.ALL, 5)
box3.Add(self.DATA, 1 , wx.ALL, 5)
box4.Add(Search, 0, wx.ALL, 5)
box5.Add(Close, 0, wx.ALL, 5)
all_box.Add(box1, 0, wx.LEFT)
all_box.Add(box2, 0, wx.LEFT)
all_box.Add(wx.StaticLine(panel), 0, wx.ALL|wx.EXPAND, 5)
all_box.Add(box3, 0, wx.CENTER)
all_box.Add(box4, 0, wx.CENTER)
all_box.Add(box5, 0, wx.CENTER)
overall.Add(all_box,0,wx.EXPAND)
overall.Add(nb, 1, wx.EXPAND)
panel.SetSizer(overall)
self.SetSize((500, 275))
self.SetTitle("Maxident Historical Data Viewer")
self.Centre()
self.Show(True)
def OnClose(self, event):
quit()
def pulldata(self, event):
firstname = str(self.FN.GetValue())
lastname = str(self.LN.GetValue())
access = pullID(firstname.strip(), lastname.strip())
dat = ""
for rec in access:
a = str(rec[0])
b = str(rec[1])
#PID = str(access.Fields("Patient Number").value)
name = str(a + ":" + b)
print name
self.DATA.Insert(name, 0)
#access.MoveNext()
access.close
def OnSelection(self, event):
x = str(self.DATA.GetStringSelection())
y = x.split(":")
PID = y[0]
#PID = "Rossini Gianni"
dati = pullfinancedata(PID)
righe =""
for line in dati:
print line
riga = str(line)
righe = righe + riga + "\n"
Publisher().sendMessage(("show.mainframe"), righe)
def pullID(name, firstname):
#name = "ROSSINI GIANNI"
#DB = r"d:\coop&mie_doc\pdci\iscritti_2007.mdb"
# db = engine.OpenDatabase(DB)
# data_source = "D:\coop&mie_doc\pdci\iscritti_2007.mdb"
# mdw ="C:\Programmi\File comuni\System\System.mdw"
# DSN = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=%s;Jet OLEDB:System Database=%s;" % (data_source, mdw)
SQL_statement = "select [name], [address] from [tessere_2008] where [name] LIKE '" + name.upper() + "%'"
#SQL_statement = "select [name], [address] from [tessere_2008] "
#access = db.OpenRecordset(sql)
# access = engine.Open(sql,conAccess,1,3)
_databasename = "d:\coop&mie_doc\pdci\iscritti_2007.mdb"
_table_name= 'tessere_2008'
_username = ''
_password = ''
_mdw = "C:\Programmi\File comuni\System\System.mdw"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User Id=%s;Password=%s;Jet OLEDB:System Database=%s;' % (_databasename, _username, _password, _mdw)
#constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:System Database=%s;' % (_databasename, _mdw)
conAccess = adodbapi.connect(constr)
accessdb = conAccess.cursor()
# accessdb = msaccess.AccessDb()
# connAccess = accessdb.connect("D:\coop&mie_doc\pdci\iscritti_2007.mdb", "Yram", "","C:\Programmi\File comuni\System\System.mdw")
print SQL_statement
accessdb.execute(SQL_statement)
print 'result rowcount shows as= %d. (Note: -1 means "not known")' \
% (accessdb.rowcount,)
# fields = access.getFields()
# print fields
# for item in access:
# print item
#get the results
access = accessdb.fetchmany(1)
#print them
for rec in access:
print rec
return accessdb
def pullfinancedata(PID):
print "pullfinancedata"
print PID
#DB = r"d:\coop&mie_doc\pdci\iscritti_2007.mdb"
#engine = win32com.client.Dispatch(r'ADODB.Recordset')
#db = engine.OpenDatabase(DB)
_databasename = "d:\coop&mie_doc\pdci\iscritti_2007.mdb"
_table_name= 'tessere_2008'
_username = ''
_password = ''
_mdw = "C:\Programmi\File comuni\System\System.mdw"
constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;User Id=%s;Password=%s;Jet OLEDB:System Database=%s;' % (_databasename, _username, _password, _mdw)
#constr = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:System Database=%s;' % (_databasename, _mdw)
conAccess = adodbapi.connect(constr)
accessdb = conAccess.cursor()
#SQL_statement = "select [name], [address] from [tessere_2008] where [name] LIKE '" + name.upper() + "%'"
SQL_statement = "select * from [Tesseramento] where [anagra_iscritto]='" + PID + "'"
#access = db.OpenRecordset(sql)
print SQL_statement
accessdb.execute(SQL_statement)
print 'result rowcount shows as= %d. (Note: -1 means "not known")' \
% (accessdb.rowcount,)
dat = ""
#while not access.EOF:
# PD = "Payment Date:\t" + str(access.Fields("Payment Date").value) + '\n'
# PM = "Payment Method:\t" + str(access.Fields("Payment Method").value) + '\n'
# PP = "Patient Payment:\t" + str(access.Fields("Patient Payment").value) + '\n'
# IP = "Insurance Payment:\t" + str(access.Fields("Insurance Payment").value) + '\n'
# dat = dat + PD + PM + PP + IP + "\n ------------------ \n"
# access.MoveNext()
"""
THIS IS WHERE I NEED HELP!
"""
#get the results
access = accessdb.fetchmany(accessdb.rowcount)
#print them
#for rec in access:
# print rec
"""
I need this dat variable to be passed to the FinanceInfo class and
i've tried FinanceInfo.Description.SetValue(dat) but its not working
"""
return access
def main():
ex = wx.App()
Frame(None)
ex.MainLoop()
if __name__ == '__main__':
main()