Issue with python tkinter sqlite3 - sqlite

I'm trying to create a registration form with python tkinter sqlite3, but I have a problem, when I do the update of just one record, all the names are updated (not just the one that was selected), and I have also this issue when I try do add new data: c.execute("INSERT INTO SCHOOL VALUES (:ID, :NAME, :BIRTH, :DOCS, :FATHER, :MOTHER, :CLASS)", sqlite3.IntegrityError: UNIQUE constraint failed: SCHOOL.CLASS, and I cant add more than 2 records.
I would like some help to solve this problem, this is the code:
from tkinter import *
from tkinter import ttk
import _sqlite3
root = Tk()
root.title('trying again')
root.geometry("1000x500")
data = [["1", "BOB", "27/10/2020", "234512", "JOHN", "DOE", "6ยบ"],
]
# conectar a database
conn = _sqlite3.connect('tree_crm.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS SCHOOL (
ID text,
NAME txt,
BIRTH txt,
DOCS txt,
FATHER txt,
MOTHER txt,
CLASS txt
oid PRIMARY KEY)
""")
# aDD RECORD TO TABLE
for record in data:
c.execute("INSERT OR IGNORE INTO SCHOOL VALUES (:ID, :NAME, :BIRTH, :DOCS, :FATHER, :MOTHER, :CLASS)",
{
'ID': str(record[0]),
'NAME': str(record[1]),
'BIRTH': str(record[2]),
'DOCS': str(record[3]),
'FATHER': str(record[4]),
'MOTHER': str(record[5]),
'CLASS': str(record[6])
}
)
conn.commit()
conn.close()
def query_database():
conn = _sqlite3.connect('tree_crm.db')
c = conn.cursor()
c.execute("SELECT oid, * FROM SCHOOL")
records = c.fetchall()
global count
count = 0
for record in records:
if count % 2 == 0:
my_tree.insert(parent='', index='end', iid=count, text='',
values=(
record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[0]),
tags=('evenrow',))
else:
my_tree.insert(parent='', index='end', iid=count, text='',
values=(
record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[0]),
tags=('oddrow',))
count += 1
print(records)
conn.commit()
conn.close()
style = ttk.Style()
style.theme_use('default')
style.configure("Treeview",
background="#D3D3D3",
foreground="black",
rowheigth=25,
filedbackground="#D3D3D3")
style.map('Treeview',
background=[('selected', "#347083")])
tree_frame = Frame(root)
tree_frame.pack(pady=10)
tree_scroll = Scrollbar(tree_frame)
tree_scroll.pack(side=RIGHT, fill=Y)
my_tree = ttk.Treeview(tree_frame, yscrollcommand=tree_scroll)
my_tree.pack()
tree_scroll.config(command=my_tree.yview)
my_tree['columns'] = ("ID", "NAME", "BIRTH", "DOCS", "FATHER", "MOTHER", "CLASS", "OID")
my_tree.column("#0", width=0, stretch=NO)
my_tree.column("ID", anchor=W, width=140)
my_tree.column("NAME", anchor=W, width=140)
my_tree.column("BIRTH", anchor=CENTER, width=100)
my_tree.column("DOCS", anchor=W, width=140)
my_tree.column("FATHER", anchor=W, width=140)
my_tree.column("MOTHER", anchor=W, width=140)
my_tree.column("CLASS", anchor=W, width=140)
my_tree.column("OID", anchor=W, width=50)
my_tree.heading("#0", text="", anchor=W)
my_tree.heading("ID", text="ID", anchor=W)
my_tree.heading("NAME", text="NAME", anchor=W)
my_tree.heading("BIRTH", text="BIRTH", anchor=CENTER)
my_tree.heading("DOCS", text="DOCS", anchor=W)
my_tree.heading("FATHER", text="FATHER", anchor=W)
my_tree.heading("MOTHER", text="MOTHER", anchor=W)
my_tree.heading("CLASS", text="CLASS", anchor=W)
my_tree.heading("OID", text="OID", anchor=W)
my_tree.tag_configure('oddrow', background="white")
my_tree.tag_configure('evenrow', background="lightblue")
data_frame = LabelFrame(root, text="INFORMATION")
data_frame.pack(fill="x", expand="yes", pady=20)
fn_ID = Label(data_frame, text="ID")
fn_ID.grid(row=0, column=0, padx=10, pady=10)
fn_ID = Entry(data_frame)
fn_ID.grid(row=0, column=1, padx=10, pady=10)
fn_NAME = Label(data_frame, text="NAME")
fn_NAME.grid(row=0, column=2, padx=10, pady=10)
fn_NAME = Entry(data_frame)
fn_NAME.grid(row=0, column=3, padx=10, pady=10)
fn_BIRTH = Label(data_frame, text="DOCS")
fn_BIRTH.grid(row=0, column=4, padx=10, pady=10)
fn_BIRTH = Entry(data_frame)
fn_BIRTH.grid(row=0, column=5, padx=10, pady=10)
fn_DOCS = Label(data_frame, text="FATHER")
fn_DOCS.grid(row=1, column=0, padx=10, pady=10)
fn_DOCS = Entry(data_frame)
fn_DOCS.grid(row=1, column=1, padx=10, pady=10)
fn_FATHER = Label(data_frame, text="MOTHER")
fn_FATHER.grid(row=1, column=2, padx=10, pady=10)
fn_FATHER = Entry(data_frame)
fn_FATHER.grid(row=1, column=3, padx=10, pady=10)
fn_MOTHER = Label(data_frame, text="CLASS")
fn_MOTHER.grid(row=1, column=4, padx=10, pady=10)
fn_MOTHER = Entry(data_frame)
fn_MOTHER.grid(row=1, column=5, padx=10, pady=10)
fn_OID = Label(data_frame, text="OID")
fn_OID.grid(row=0, column=6, padx=10, pady=10)
fn_OID = Entry(data_frame)
fn_OID.grid(row=0, column=7, padx=10, pady=10)
fn_CLASS = Label(data_frame, text="BIRTH")
fn_CLASS.grid(row=1, column=6, padx=10, pady=10)
fn_CLASS = Entry(data_frame)
fn_CLASS.grid(row=1, column=7, padx=10, pady=10)
# add records:
def add_records():
my_tree.insert(parent='', index='end', text='',
values=(
fn_ID.get(), fn_NAME.get(), fn_CLASS.get(), fn_BIRTH.get(), fn_DOCS.get(),
fn_FATHER.get(),
fn_MOTHER.get(), fn_OID.get()), )
# update records:
def update_records():
select = my_tree.focus()
my_tree.item(select, text="", values=(
fn_ID.get(), fn_NAME.get(), fn_CLASS.get(), fn_BIRTH.get(), fn_DOCS.get(), fn_FATHER.get(),
fn_MOTHER.get(),
), )
conn = _sqlite3.connect('tree_crm.db')
c = conn.cursor()
c.execute("""UPDATE OR IGNORE SCHOOL SET
ID=:ID,
NAME=:NAME,
BIRTH=:BIRTH,
DOCS=:DOCS,
MOTHER=:MOTHER,
CLASS=:CLASS
WHERE oid=oid""",
{
'ID': fn_ID.get(),
'NAME': fn_NAME.get(),
'BIRTH': fn_BIRTH.get(),
'DOCS': fn_DOCS.get(),
'FATHER': fn_FATHER.get(),
'MOTHER': fn_MOTHER.get(),
'CLASS': fn_CLASS.get(),
}
)
conn.commit()
conn.close()
# MOVE UP
def up():
rows = my_tree.selection()
for row in rows:
my_tree.move(row, my_tree.parent(row), my_tree.index(row) - 1)
# MOVE DOWN
def down():
rows = my_tree.selection()
for row in reversed(rows):
my_tree.move(row, my_tree.parent(row), my_tree.index(row) + 1)
# DELETE RECORDS SPECIFIC
def remove_one():
x = my_tree.selection()
for record in x:
my_tree.delete(record)
def remove_all():
for record in my_tree.children():
my_tree.delete(record)
# delete all
def clear_record():
fn_ID.delete(0, END)
fn_NAME.delete(0, END)
fn_CLASS.delete(0, END)
fn_BIRTH.delete(0, END)
fn_DOCS.delete(0, END)
fn_FATHER.delete(0, END)
fn_MOTHER.delete(0, END)
fn_CLASS.delete(0, END)
# SELECT RECORD
def select_record(e):
fn_ID.delete(0, END)
fn_NAME.delete(0, END)
fn_CLASS.delete(0, END)
fn_BIRTH.delete(0, END)
fn_DOCS.delete(0, END)
fn_FATHER.delete(0, END)
fn_MOTHER.delete(0, END)
fn_CLASS.delete(0, END)
fn_OID.delete(0, END)
selected = my_tree.focus()
values = my_tree.item(selected, 'values')
# insert values
fn_ID.insert(0, values[0])
fn_NAME.insert(0, values[1])
fn_CLASS.insert(0, values[2])
fn_BIRTH.insert(0, values[3])
fn_DOCS.insert(0, values[4])
fn_FATHER.insert(0, values[5])
fn_MOTHER.insert(0, values[6])
fn_OID.insert(0, values[7])
# add butons:
button_frame = LabelFrame(root, text="COMANDOS")
button_frame.pack(fill="x", expand="yes", padx=20)
update_button = Button(button_frame, text="changing data", command=update_records)
update_button.grid(row=0, column=0, padx=10, pady=10)
add_button = Button(button_frame, text="add data", command=add_records)
add_button.grid(row=0, column=1, padx=10, pady=10)
remove_button = Button(button_frame, text="remove data", command=remove_one)
remove_button.grid(row=0, column=2, padx=10, pady=10)
select_button = Button(button_frame, text="clear data", command=clear_record)
select_button.grid(row=0, column=3, padx=10, pady=10)
move_button = Button(button_frame, text="move row down", command=down)
move_button.grid(row=0, column=4, padx=10, pady=10)
move_button = Button(button_frame, text="move row up", command=up)
move_button.grid(row=0, column=5, padx=10, pady=10)
# delete_button = Button(button_frame, text="remover tudo",command=remove_all)
# delete_button.grid(row=0, column=7, padx=10, pady=10)
my_tree.bind("<ButtonRelease-1>", select_record)
query_database()
root.mainloop()

Related

Unable to reconnect to a socket

I am trying to connect to a socket using a client that is running Tkinter. The script runs a banking app allowing users to log in. The user data is stored in an SQLite database. When running the socket and client scripts the Tkinter window launches and the user is able to log in. However, when the user logs out and tries to log in as another user the program gets stuck.
LogInCommand() I think is getting stuck as it only fails when running again. I believe it has to do with how I am discounting from the socket. However, I need the socket to constantly run for the app to work.
Socket :
import socket
import sqlite3
Connection = sqlite3.connect('BankAccounts.sqlite')
st = socket.socket() #Creating a socket object. Second socket is the class.
print("socket ready")
st.bind(("Localhost",8080)) #Creating the socket using port 8080 (IP address + port number)
st.listen(100) #Only allowing a maximum of two connections at a time.
print("waiting for connections")
while True:
Client, address = st.accept() #Creating two variables and setting them equal to the accept object method.
# print("connected with", address)
print("Banking")
cdata = Client.recv(1024).decode()
print("in loop")
if not cdata:
break
if "*li#" in cdata:
print(cdata)
data = cdata.split("*li#")
cred = data[1].split("##")
sql = "SELECT * FROM bankusers"
curser = Connection.execute(sql)
username = cred[0]
password = cred[1]
for row in curser:
if row[0] == username and row[1] == password:
balance = str(row[2])
print(type(balance))
login = ("*Suc*"+balance)
print(login)
Client.send(bytes(f"{login}",'utf-8'))
Client.close()
Client :
from tkinter import *
from tkinter import *
from Bank import *
import socket
root = Tk()
Client = socket.socket()
Client.connect(("Localhost",8080))
import json
login = "Failed"
import sqlite3
Connection = sqlite3.connect('BankAccounts.sqlite')
def localuser(username,password,balance):
user1 = {
"username": username,
"password": password,
"balance" : balance
}
return user1
def sqlupdate():
with open("bankusers.json","r") as file:
reader = json.load(file)
balance2 = reader["balance"]
username2 = reader["username"]
print(balance2)
print(username2)
sql = f"UPDATE bankusers SET balance = {balance2} where username = '{username2}'"
Connection.execute(sql)
Connection.commit()
def updatenewuser(username, amount):
try:
sql1 = f"Select * from bankusers where username = '{username}' "
data = Connection.execute(sql1)
for row in data:
newbalance = int(row[2]) + int(amount)
sql2 = f"Update bankusers Set balance = {newbalance} where username = '{username}'"
Connection.execute(sql2)
except:
print("The user does not exist")
def logout():
canvas.delete("all")
label1 = Label(root,text = "Username")
label2 = Label(root,text = "Password")
global usernamebox
global passwordbox
usernamebox = Entry(root,width = 20)
passwordbox = Entry(root,width = 20)
buttonLogin = Button(root,text = "Login",width=10, command=LoginCommand)
canvas.create_window(230,100,window = label1)
canvas.create_window(230,150,window = label2)
canvas.create_window(400,100,window = usernamebox)
canvas.create_window(400,150,window = passwordbox)
canvas.create_window(400,200,window = buttonLogin)
canvas.pack()
def pay():
if name.get()==username1:
trylabel = Label(root,text= "You are unable to send money to yourself",)
canvas.create_window(400,250,window=trylabel)
else:
canvas.delete("all")
try:
sql2 = f"SELECT * FROM bankusers where username = '{username1}'"
curser = Connection.execute(sql2)
for row in curser:
if int(amountbox.get()) <= row[2]:
print("Sent")
newamount = row[2] - int(amountbox.get())
with open("bankusers.json", "w") as file:
user = localuser(username1,password1,newamount)
json.dump(user,file,indent=3)
sqlupdate()
updatenewuser(name.get(),int(amountbox.get()))
label1 = Label(root,text="Transaction Succsfull")
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,100,window=label1)
canvas.create_window(400,200,window=backbut)
else:
canvas.delete("all")
label1 = Label(root,text = "Transaction Failed. Please ensure you have suffcient funds for this transaction")
canvas.create_window(400,200,window=label1)
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,300,window=backbut)
except:
label1 = Label(root,text = "Transaction Failed. Please check recipient name and amount")
canvas.create_window(400,200,window=label1)
backbut = Button(root,text= "Done", command=mainscreen)
canvas.create_window(400,300,window=backbut)
def transact():
print("")
canvas.delete("all")
global name
label1 = Label(root,text = "Person Receiving:")
label2 = Label(root,text = "Amount:")
name = Entry(root,width = 20)
global amountbox
amountbox = Entry(root,width = 20)
paybutt = Button(root,text = "Pay", command = pay)
backbutton = Button(root,text = "Back",command = mainscreen)
canvas.create_window(350,300,window=backbutton)
canvas.create_window(450,100,window = name)
canvas.create_window(250,100,window=label1)
canvas.create_window(250,200,window=label2)
canvas.create_window(450,300,window=paybutt)
canvas.create_window(450,200,window=amountbox)
return
def LoginCommand():
count = 1
li = "*li#"
cred = li+usernamebox.get()+"##"+passwordbox.get()
Client.send((bytes(cred,"utf-8")))
message = Client.recv(1024).decode()
print(message)
if "*Suc*" in message:
count = 0
login = "Succsess"
global username1
global password1
global balance1
username1 = usernamebox.get()
password1 = passwordbox.get()
usernamebox.destroy()
passwordbox.destroy()
canvas.delete("all")
balance1 = message.split("*Suc*")
user = localuser(username1,password1,balance1[1])
with open("bankusers.json", "w") as file:
json.dump(user,file,indent=3)
mainscreen()
if count == 1:
global label2
label2 = Label(root,text = "Login Failed. Please Try Again")
canvas.create_window(400,250,window = label2)
def mainscreen():
with open("bankusers.json","r") as file:
reader = json.load(file)
balance2 = reader["balance"]
label2.destroy()
canvas.delete("all")
label1 = Label(root, text = f"Available Balance: R{balance2}")
buttonLogout = Button(root,text = "Log Out", command=logout)
buttonTrans = Button(root,text = "Transact", command=transact)
canvas.create_window(400,100,window = label1)
canvas.create_window(350,200,window=buttonLogout)
canvas.create_window(450,200,window = buttonTrans)
canvas.pack()
root.title("Raindrop Bank")
canvas = Canvas(root, width = 800, height = 400)
label1 = Label(root,text = "Username")
label2 = Label(root,text = "Password")
usernamebox = Entry(root,width = 20)
passwordbox = Entry(root,width = 20)
buttonLogin = Button(root,text = "Login",width=10, command=LoginCommand)
canvas.create_window(230,100,window = label1)
canvas.create_window(230,150,window = label2)
canvas.create_window(400,100,window = usernamebox)
canvas.create_window(400,150,window = passwordbox)
canvas.create_window(400,200,window = buttonLogin)
canvas.pack()
root.mainloop()

How to send nicely formatted mails in R

I use below mentioned code to send mails, can I change the format of table which will pasted on mail body, I want to send nicely formatted/compacted table in mail body.
first6 is my data.frame
Date=sys.Date()-1
date2 <- paste("My subject of mail", Date, sep = " - ")
setwd("/xyz")
newdir <- paste("output", Sys.time(), sep = "_")
dir.create(newdir)#, showWarnings = FALSE)
setwd(newdir)
######
mydoc = bsdoc( title = 'my document')
options( "ReporteRs-fontsize" = 8 )
mydoc = addParagraph(mydoc, value = "Hi All, \n\nPlease check attached summary.")
mydoc = addParagraph(mydoc, value = "Summary:")
MyFTable = FlexTable( data = first6, add.rownames = FALSE, header.cell.props = cellProperties( background.color = "#FAEBD7" )
, header.par.props = parProperties(text.align = "center" ))
MyFTable = setColumnsColors( MyFTable, j=1, colors = '#F0F8FF' )
MyFTable[ , ] = parProperties( text.align = 'center')
MyFTable = setColumnsColors( MyFTable, j=ncol(first6), colors = '#F0F8FF' )
mydoc = addFlexTable( mydoc, MyFTable )
writeDoc( mydoc, file = "op2.html" )
send.mail(from = "abc#xyz.com",
to = c("abc#xyz.com"),
subject = date2,
body = "op2.html",
html = TRUE,
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "abc#xyz.com", passwd = "xyz#123", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
Sorry if this doesn't answer your question, but I think you need to use the right tool for the right job.
In column A : Names of the people
In column B : E-mail addresses
In column C:Z : Filenames like this C:\Data\Book2.xls (don't have to be Excel files)
The Macro will loop through each row in "Sheet1" and if there is a E-mail address in column B
and file name(s) in column C:Z it will create a mail with this information and send it.
Sub Send_Files()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the path/file names in the C:Z column in each row
Set rng = sh.Cells(cell.Row, 1).Range("C1:Z1")
If cell.Value Like "?*#?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "Testfile"
.Body = "Hi " & cell.Offset(0, -1).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
You can find other options at the link below.
https://www.rondebruin.nl/win/s1/outlook/mail.htm

Physical button interacting with tkinter button widget

I'm making an app to run with my Raspberry Pi with Tkinter GUI. The app allready runs well. Now I want to use 2 physical buttons wired to GPIOS that interact with two of the buttons widgets I have in the app. Thanks to helpers in forums I found the way to do it as You can see in the code. But now I need to disabled in some way the physical button in order to avoid accidental push meanwhile the scripts run, as I can easly do with the widgets. I've been googling a lot but I din not found any example of whaT i need. Can some one give me orientation about the method to obtain this. Thanks in advance.
from Tkinter import *
import RPi.GPIO as GPIO
root = Tk()
root.geometry("320x480")
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN,pull_up_down=GPIO.PUD_UP)
shootdelay = 12 #12
shootinterval = 7#7
shootnumber = 5#12
videodelay = 3
selft = 5
newset = 0
endvideo = 5
intertext = "(D:" + str(shootdelay) + ")(I:" + str(shootinterval) + ")(T:" + str(shootnumber) + ")"
flagselftim = 0
flagvideo = 0
videosetmode = 0
flagsetings = 0
flagcancel = 0
flagnewset = 0
secDelay = shootdelay
secInterv = shootinterval
secSelftim = selft
secvideo = videodelay
remainshots = shootnumber
secshoots = shootnumber - 1
seccompte = 0
readyshoots =
class intervalometer:
def __init__(self, master):
self.textBox = Text(root, height=1, width=1, relief=SUNKEN, font=('arial narrow', 17, 'normal'), bg="green",
fg="white")
self.textBox.grid(row=1, column=1, padx=3, pady=2, sticky=NSEW)
self.textBox.insert(END, "READY")
self.botshoot = Button(root, width=18, font=('arial narrow', 19, 'normal'), text="START",
activebackground="#00dfdf")
self.botshoot.grid(row=4, rowspan=2, column=0, columnspan=2, ipady=15, pady=2, sticky=NSEW)
self.botshoot.configure(command=self.start)
self.botStop = Button(root, heigh=2, font=('arial', 18, 'normal'), text="STOP/RESET", activebackground="red")
self.botStop.grid(row=13, rowspan=3, column=0, pady=1, sticky=NSEW)
self.botStop.configure(state=DISABLED, command=self.stop)
self.botQuit = Button(root, width=3, font=('arial', 18, 'normal'), text="QUIT", activebackground="red",
state=NORMAL)
self.botQuit.grid(row=13, rowspan=3, column=1, pady=1, sticky=NSEW)
self.botQuit.configure(command=self.closewindow)
GPIO.add_event_detect(18, GPIO.RISING, callback=self.start, bouncetime=200)
def start(self, *args, **kwargs):
global flagselftim
self.count = 0
self.cancel_id = None
self.botshoot.configure(state=DISABLED)
self.botStop.configure(state=NORMAL)
self.botQuit.configure(state=DISABLED)
self.start_shoot_delay()
def stop(self):
global secDelay
global secSelftim
global selft
global flagvideo
global videosetmode
global secvideo
global remainshots
global secInterv
global readyshoots
flagvideo = 0
videosetmode = 0
secDelay = shootdelay
secInterv = shootinterval
secvideo = videodelay
selft = 5
secSelftim = selft
remainshots = shootnumber
readyshoots = 1
if self.cancel_id is not None:
self.textBox.after_cancel(self.cancel_id)
self.cancel_id = None
self.textBox.insert(END, 0)
self.textBox.delete("1.0", END)
self.botshoot.configure(text="START")
self.botshoot.configure(state=NORMAL)
self.botStop.configure(state=DISABLED)
self.botQuit.configure(state=NORMAL)
self.textBox.insert(END, "READY")
self.textBox.configure(font=('arial narrow', 17, 'normal'), bg="green", fg="white")
def closewindow(self):
root.destroy()
def start_shoot_delay(self):
global secDelay
if secDelay > 9:
contador = " " + str(secDelay)
else:
contador = " " + str(secDelay)
self.textBox.delete("1.0", END)
self.textBox.configure(font=('arial narrow', 17, 'normal'), bg="red", fg="white")
self.botshoot.configure(state=DISABLED)
if self.count < shootdelay:
self.count += 1
self.textBox.insert(END, contador)
self.cancel_id = self.textBox.after(1000, self.start_shoot_delay)
secDelay -= 1
else:
self.count = 0
secDelay = shootdelay
self.start_shoot_interval()
def start_shoot_interval(self):
global secInterv
if remainshots == shootnumber:
self.start_shootings()
else:
if secInterv > 9:
contador = " " + str(secInterv)
else:
contador = " " + str(secInterv)
self.textBox.delete("1.0", END)
self.textBox.configure(font=('arial narrow', 17, 'normal'), bg="red", fg="white")
if self.count < shootinterval:
self.count += 1
self.textBox.insert(END, contador)
self.cancel_id = self.textBox.after(1000, self.start_shoot_interval)
secInterv -= 1
else:
self.count = 0
secInterv = shootinterval
self.start_shootings()
def start_shootings(self):
global remainshots
global videosetmode
global readyshoots
global secSelftim
global selft
remainshots -=1
if secSelftim <5:
txtremain = "SHOOTING = " + str(1) + "/" + str(1)
else:
txtremain = "REMAINING = " + str(remainshots) + "/" + str(shootnumber)
print "BEEP shoot nr",readyshoots, "av", shootnumber
readyshoots +=1
if remainshots >0:
self.start_shoot_interval()
else:
print "BEEP-BEEP-BEEP : end of roll"
self.etstatus.configure(text="END OF ROLL")
root.update_idletasks()
root.after(500)
readyshoots = 1
selft = 5
self.textBox.insert(END, "READY")
self.textBox.configure(font=('arial narrow', 17, 'normal'), bg="green", fg="white")
self.botshoot.configure(state=NORMAL)
self.botStop.configure(state=DISABLED)
self.botQuit.configure(state=NORMAL)
remainshots = shootnumber
intervalometer(root)
root.mainloop()
I don't see how this is even an issue since the start method should lock up the entire program, including the input from the button. If the button detection is in it's own thread or something, you could just add a check. The easiest thing to check is the tk Button state:
def start(self, *args, **kwargs):
if self.botshoot['state'] == DISABLED:
print 'already running'
return # abort this method
self.botshoot.configure(state=DISABLED)
# etc ...

Must declare the scalar variable "#useridaUPDATE"

sqlqrystrng = "UPDATE temp_user_details set user_name = #username, user_email = #useremail, user_contact = #usercontact, user_address=#useraddress WHERE user_id = #userida"
sqlqrystrng2 = "UPDATE user_type set user_password = #userpassword where user_id = #useridb"
string_cnct = sqlqrystrng & sqlqrystrng2
conn.open
cmd = New SqlCommand(string_cnct, conn)
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#userida"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#useridb"
cmd.Parameters.Item("#userida").Value = struserid
cmd.Parameters.Item("#useridb").Value = struserid
sqlqrystrng = "UPDATE temp_user_details set user_name = #username, user_email =
useremail, user_contact = #usercontact, user_address=#useraddress WHERE user_id =
userida"
sqlqrystrng2 = " UPDATE user_type set user_password = #userpassword where user_id = #useridb"
string_cnct = sqlqrystrng & sqlqrystrng2
conn.open
cmd = New SqlCommand(string_cnct, conn)
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#userida"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#useridb"
cmd.Parameters.Item("#userida").Value = struserid
cmd.Parameters.Item("#useridb").Value = struserid
You need to add space before Update in second string

CommandText is not initialized

I have this code
Dim LogData As sterm.markdata = New sterm.markdata()
Dim datelistquery As String
Dim properdate As String
If Session("TenHolStDateHP1") = "%" or Session("TenHolStDateHP1") = "" Then
If Session("passedPropId") = "" Then
'QUERY USED IF NO DATE SELECTED AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF NO DATE SELECTED AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
End If
Else
If Session("holidayduration") = "7" Then
If Session("passedPropId") = "" Then
'QUERY USED IF DATE SELECTED AND 7 NIGHTS AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF DATE SELECTED AND 7 NIGHTS AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
End If
Else If Session("holidayduration") = "14" Then
theyear = Left(Session("TenHolStDateHP1"), 4)
theweek = Right(Session("TenHolStDateHP1"), 2)
If theweek < "52" then
theyear = theyear
If theweek < "10" then
theweek = "0" & theweek + 1
Else
theweek = theweek + 1
End If
Else
If (theyear = "2015" and theweek < "53") or (theyear = "2020" and theweek < "53") or (theyear = "2026" and theweek < "53") or (theyear = "2032" and theweek < "53") or (theyear = "2037" and theweek < "53") then
theyear = theyear
theweek = "53"
Else
theyear = theyear + 1
theweek = "01"
End If
End If
If Session("passedPropId") = "" Then
'QUERY USED IF DATE SELECTED AND 14 NIGHTS AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week in (''"&Session("TenHolStDateHP1")&"'',''"& theyear & theweek &"'') AND on_hold = ''NO'' AND booked = ''NO'' GROUP BY property_id HAVING count(property_id) > 1 ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF DATE SELECTED AND 14 NIGHTS AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week in (''"&Session("TenHolStDateHP1")&"'',''"& theyear & theweek &"'') AND on_hold = ''NO'' AND booked = ''NO'' GROUP BY property_id HAVING count(property_id) > 1 ') ORDER BY number_slept, property_id"
End If
Else If Session("holidayduration") = "3/4" Then
If Session("passedPropId") = "" Then
'QUERY USED IF DATE SELECTED AND 3/4 NIGHTS AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE (part_full_flag = ''P'' or split_weeks = ''Y'') AND location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF DATE SELECTED AND 3/4 NIGHTS AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE (part_full_flag = ''P'' or split_weeks = ''Y'') AND location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
End If
End If
'Query to get date in nice format
properdate = "SELECT * FROM openquery ("+Application("hpbDsrc")+", 'SELECT starting_period from web_header WHERE year_week = ''"&Session("TenHolStDateHP1")&"'' ')"
Dim drCode7 As DataSet = LogData.StermQ3(properdate)
dgAvailable2.DataSource = drCode7.Tables(0).DefaultView
dgAvailable2.DataBind()
End If
dd1.DataSource = LogData.StermQ3(datelistquery).Tables(0).DefaultView
dd1.DataBind()
dd1.Items.Insert(0, new listitem("Any location", "%"))
And the error CommandText has not been initialized keeps showing up on the IIS event viewer log
I can't replicate the problem myself but I know it is happening can anyone suggest anything
The error says it happens with this line dd1.DataSource = LogData.StermQ3(datelistquery).Tables(0).DefaultView
Thanks
Jamie
I think you are in a situation where none of the following conditions are met:
Session("TenHolStDateHP1") = "%"
Session("TenHolStDateHP1") = ""
Session("holidayduration") = "3/4"
Session("holidayduration") = "14"
Session("holidayduration") = "7"
Since you don't initialize datelistquery to anything and you end in an else if it seems possible that you are not assigning a query to this string and could pass an empty string to your StermQ3 function.
You may want to add an else statement to the end of your chain of if/else if statements as a catchall. What you would set datelistquery to in the else statement depends on what you are doing.

Resources