Programming error with SQlite3 - python

i am getting the below errors
Traceback (most recent call last):
File "D:\PYTHON SUPER INP\DB test - Copy1220.py", line 29, in <module>
if __name__ == "__main__":main()
File "D:\PYTHON SUPER INP\DB test - Copy1220.py", line 17, in main
addCust("Zach")
File "D:\PYTHON SUPER INP\DB test - Copy1220.py", line 13, in addCust
VALUES(?)""",(name))
ProgrammingError: Incorrect number of bindings supplied. The current
statement uses 1, and there are 4 supplied.
with my follwing code
import sqlite3
createDb = sqlite3.connect(":memory:")
queryCurs = createDb.cursor()
def createTable():
queryCurs.execute(''' CREATE TABLE customers
(id INTEGER PRIMARY KEY, name TEXT)''')
def addCust(name):
queryCurs.execute("""INSERT INTO customers (name)
VALUES(?)""",(name))
def main():
createTable()
addCust("Zach")
createDb.commit()
queryCurs.execute("SELECT * FROM customers")
for i in queryCurs:
print "/n"
for j in i:
print j
queryCurs.close
if __name__ == "__main__":main()

Here:
def addCust(name):
queryCurs.execute("""INSERT INTO customers (name)
VALUES(?)""",(name))
When you do (name) it's the same as name - so if name is "Zach" then it's a string, that's iterable and has a length of 4, instead, make it a one tuple or a list, eg:
(name,) # notice the trailing comma
eg:
>>> len(('Zach')) # same as len('Zach')
4
>>> len(('Zach',)) # now a one-tuple containing a string of length 4
1
Couple of other notes - see code comments:
for i in queryCurs:
print "/n" # <-- to print a new line - use `\n` - not `/n`
for j in i:
print j
queryCurs.close # this should be queryCurs.close() (eg - call the method)

Related

For-loop exiting prematurely

I'm having an issue where a python for loop is exiting prematurely. The loop iterates over SQL database entries by location.
If location is found, it will grab the IP address of those entries and send a configuration. If the job fails, or throws an exception in my case, within the exception it will go to a function to update the status, date/time. The expected result currently is an exception.
When it comes back to the original function, it exits the loop and doesn't go to the next DB entry (which I know is there.) If I remove the function from within the exception then everything works fine.
Current results. It shows the loop working from function to function. I should see twice, or 6 lines:
Return to Function,
Back to function,
Finished,
Return to Function,
Back to function,
Finished,
Here's what I'm getting
1. IP
2. Status
3. Location
4. Main
Selection: 3
Location: Test
Return to Function,
Back to function,
Finished,
Code shown below:
def db_entry(Device, status):
int = 0
while int < 1:
c.execute('SELECT * FROM Automation WHERE Device=?', (Device,))
if bool(c.fetchone()) == True:
c.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?"(time.strftime("%H:%M:%S +0000"), date.today(), status, Device))
mydb.commit()
int = int + 1
else:
c.execute("INSERT INTO Automation VALUES ('%s','NETCONF','POC', '%s', '%s', '%s')" % (Device, status, date.today(), time.strftime("%H:%M:%S +0000")))
mydb.commit()
int = int + 1
else:
print("Return to Function")
def send_single_configuration(file):
status_1 = "Success"
status_2 = "Fail"
print("\n")
view_database()
print("\n")
retries = 0
print("1. IP")
print("2. Status")
print("3. Location")
print("4. Main")
print("\n")
input_selection = input("Selection: ")
print("\n")
if input_selection == "3":
location = input("Location: ")
for row in c.execute('SELECT * FROM Automation WHERE Location=?', (location, )):
try:
m = manager.connect(row[0], 830, "cisco", "cisco", {'name': 'csr'})
config_file = open(file=file).read()
m.edit_config(config_file, target="running")
db_entry(row[0], status_1)
print("\n")
print("Configuration Complete!")
print("\n")
except AttributeError:
db_entry(row[0], status_2)
print("Back to function")
else:
print("Finished")
Traceback (most recent call last):
File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 412, in <module>
main()
File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 82, in main
snmp_configuration()
File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 326, in snmp_configuration
send_single_configuration(SNMP_file)
File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 395, in send_single_configuration
m.edit_config(config_file, target="running")
AttributeError: 'NoneType' object has no attribute 'edit_config'
More Testing:
If i remove everything but a print statement from the db_entry function which gave the expected result.
I'm thinking something withing this line of code or something with the module/progam interaction.
c.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE
Device=?",(time.strftime("%H:%M:%S +0000"), date.today(), status,
Device))
It was the sqlite3 module. I found an old answer from 8 years ago here, python sqlite3 for loop update.
sqllitle3 module doesn't allow for multi-threading.
I created another connection object and used it to update the DB entry
c = mydb.cursor() # Find the location
d = mydb.cursor() # Update the entry
for row in c.execute('SELECT * FROM Automation WHERE Location=?', (location, )):
try:
device_connect(row[0])
for capability in m.server_capabilities:
continue
d.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?",(time.strftime("%H:%M:%S +00"), date.today(), status_1, row[0],))
mydb.commit()
except AttributeError:
d.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?",(time.strftime("%H:%M:%S +00"), date.today(), status_2, row[0],))

task() got multiple values for keyword argument 'appdynhost'

I am simply trying to receive an input, run it through some if, elif conditions and replace certain text from a bunch of lines :
def task(appdynhost):
if (appdynhost) == "security":
appdynpass = 'xxxxxxxx'
elif (appdynhost) == "security2":
appdynpass = 'yyyyyyyy'
elif (appdynhost) == "security3":
appdynpass = 'zzzzzzzz'
elif (appdynhost) == "security4":
appdynpass = 'wwwwwwww'
replacements = {'<controller_name>':appdynhost,'<controller_password>';appdynpass}
s = r"""
"standardenv::v2_0_0_0_0":
"appgroups::v1_0_0_0_0":
definitions:
jdk: {gid: 5007}
app: {gid: 5008}
"appusers::v1_0_0_0_0":
definitions:
jdk: {group: jdk, uid: 5007}
app: {group: app, uid: 5008}
"jdk::v1_7_45_2_0::standard":
instance_owner: jdk
instance_group: jdk
"app::v1_1_2_1_0::standard":
instance_owner: app
instance_group: app
controller_host: "<controller_name>.saas.com"
account_name: "<controller_name>"
account_password: "<controller_password>" """
line=s.split()
for line in s.splitlines():
for src, target in replacements.iteritems():
line = line.replace(src, target)
lines.append(line)
with open('DC_mcp.yaml', 'w') as outfile:
for line in lines:
outfile.write(line + '\n')
print (line)
I am getting this error :
Traceback (most recent call last):
File "build/bdist.linux-x86_64/egg/bdblib/task_runner.py", line 72, in run_bdblib_task
File "build/bdist.linux-x86_64/egg/bdblib/run.py", line 38, in run
return task_module.task(env, **inputs)
TypeError: task() got multiple values for keyword argument 'appdynhost'
I am getting the input for appdynhost as a raw input. I am not sure whats going wrong.
You definition of "task" function only has one argument which you named "appdynhost".
def task(appdynhost):
...
Your call however has several:
return task_module.task(env, **inputs)
TypeError: task() got multiple values for keyword argument 'appdynhost'
At either the function or the call you'll need to fix the inputs.

String interpolation TypeError: not enough arguments for format string

I am trying to use the Python string interpolation with %s for my parameter variable. My variable is name and the value in this variable I would like to insert it where I have put %s. My code snippet is:
def select_dataset(self, name):
# Params name: The name of the dataset e.g. CRM
name_element = self.get_element(By.XPATH, '//table[#id="data_configuration_datasets_ct_fields_body"]/tbody/tr/td/div/span[#title="%s" and contains(text(), "%s")]/preceding::input[1]' % name % name).click()
The error is:
Traceback (most recent call last):
File "C:\Webdriver\ClearCore Regression Test\ClearCore - Regression Test\TestCases\DatasetsPage_TestCase.py", line 146, in test_a2_edit_datasets
ds.select_dataset("Edit_test")
File "C:\Webdriver\ClearCore Regression Test\ClearCore - Regression Test\Pages\datasets.py", line 281, in select_dataset
name_element = self.get_element(By.XPATH, '//table[#id="data_configuration_datasets_ct_fields_body"]/tbody/tr/td/div/span[#title="%s" and contains(text(), "%s") % name]/preceding::input[1]' % name).click()
TypeError: not enough arguments for format string
The line where the %s and %name is here:
name_element = self.get_element(By.XPATH, '//table[#id="data_configuration_datasets_ct_fields_body"]/tbody/tr/td/div/span[#title="%s" and contains(text(), "%s")]/preceding::input[1]' % name % name).click()
The Test Case which calls the method:
def test_a2_edit_datasets(self):
print "*** Test edit_dataset ***"
menu_bar = MenuBarPage(self.driver)
tool_bar = ToolbarPage(self.driver)
project_navigator = ProjectNavigatorPage(self.driver)
ds = project_navigator.select_projectNavigator_item("Datasets")
ds.click_add_datasets()
time.sleep(1)
ds.add_datasets_name_description_and_datamap("Edit_test", Globals.dataset_description) # adds the name, description and selects datamap drop down for the Dataset
ds.add_name_type_and_size_for_key_fields(Globals.dataset_crm_name_keyField, Globals.dataset_type_string)
ds.click_save_datasets()
#ds.select_dataset(Globals.dataset_name_crm)
ds.select_dataset("Edit_test")
Where should I put the %?

SQLite 3: sqlite InterfaceError: Error binding parameter 0 - probably unsupported type

I am using sqlite3 python modules and th following code returns the error
> Exception in Tkinter callback Traceback (most recent call last):
> File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
> return self.func(*args) File "C:\MonitorSoft\MonitorSoft.py", line 199, in LoadSQL
> CurFiles.execute('SELECT * FROM Files WHERE CheckSum = ?', (WinRedactor.Table.item(WinRedactor.Table.selection()[0],
> option='values')[3],))
>
> sqlite3.InterfaceError: Error binding parameter 0 - probably
> unsupported type.
def LoadSQL(event):
con = sqlite3.connect('C:/MonitorSoft/SoftMon.db')
CurPackets = con.cursor()
CurFiles = con.cursor()
CurFilesIn = con.cursor()
curFilesPackets = con.cursor()
CurPackets.execute('SELECT * FROM Packets WHERE PacketName = ?', (WinRedactor.Combobox.get(),))
for RowPackets in CurPackets:
if WinRedactor.Combobox.get() !='NULL':
while WinRedactor.Table.selection() != '':
CurFilesIn.execute('INSERT INTO Files (id, FilePath, FileName, Size, CheckSum) VALUES(NULL, ?, ?, ?, ?)',((WinRedactor.Table.item(WinRedactor.Table.selection()[0], option='values')[0]), (WinRedactor.Table.item(WinRedactor.Table.selection()[0], option='values')[1]), (WinRedactor.Table.item(WinRedactor.Table.selection()[0], option='values')[2]),(WinRedactor.Table.item(WinRedactor.Table.selection()[0], option='values')[3])))
con.commit()
CurFiles.execute('SELECT * FROM Files WHERE CheckSum = ?', (WinRedactor.Table.item(WinRedactor.Table.selection()[0], option='values')[3],))
for RowFiles in CurFiles:
if RowFiles[4] == (WinRedactor.Table.item(WinRedactor.Table.selection()[0], option='values')[3]):
curFilesPackets.execute('INSERT INTO FilesPackets (IDFile, IDPacket) VALUES(?,?)',((RowFiles[0]), (RowPackets[0])))
con.commit()
WinRedactor.Table.delete(WinRedactor.Table.selection()[0])
con.commit()
con.close()
BtnLoadSQL = Button(WinRedactor)
BtnLoadSQL["text"] = "LOAD SQL"
BtnLoadSQL.bind("<Button-1>",LoadSQL)
BtnLoadSQL.pack()
What the problem?
Concluded the data as you wrote.
The data are the same everywhere.
The error appears randomly on different lines.
Here's an example of what gives the output as you wrote:
selection is ('I04C', 'I04D', 'I04E', 'I04F', 'I050', 'I051', 'I052', 'I053', 'I054', 'I055', 'I056', 'I057', 'I058', 'I059', 'I05A', 'I05B', 'I05C', 'I05D', 'I05E', 'I05F', 'I060', 'I061', 'I062', 'I063', 'I064', 'I065', 'I066', 'I067', 'I068', 'I069', 'I06A', 'I06B', 'I06C', 'I06D', 'I06E', 'I06F', 'I070', 'I071', 'I072', 'I073', 'I074', 'I075', 'I076', 'I077', 'I078', 'I079', 'I07A', 'I07B', 'I07C', 'I07D', 'I07E', 'I07F', 'I080', 'I081', 'I082', 'I083', 'I084', 'I085', 'I086', 'I087', 'I088', 'I089', 'I08A', 'I08B', 'I08C', 'I08D', 'I08E', 'I08F', 'I090', 'I091', 'I092', 'I093', 'I094', 'I095', 'I096', 'I097', 'I098', 'I099', 'I09A', 'I09B', 'I09C', 'I09D', 'I09E', 'I09F', 'I0A0', 'I0A1', 'I0A2', 'I0A3', 'I0A4', 'I0A5', 'I0A6', 'I0A7', 'I0A8', 'I0A9', 'I0AA', 'I0AB', 'I0AC', 'I0AD', 'I0AE', 'I0AF', 'I0B0', 'I0B1', 'I0B2', 'I0B3', 'I0B4', 'I0B5', 'I0B6', 'I0B7', 'I0B8', 'I0B9', 'I0BA', 'I0BB', 'I0BC', 'I0BD', 'I0BE', 'I0BF', 'I0C0', 'I0C1', 'I0C2', 'I0C3', 'I0C4', 'I0C5', 'I0C6', 'I0C7', 'I0C8', 'I0C9', 'I0CA')
first selection is I04C
values are ('C:\\WINDOWS\\Resources\\Themes\\Luna\\Shell\\Metallic', 'shellstyle.dll', '362496', '05b3f32c7f3bd125446d024a30373c9d')
checksum: 05b3f32c7f3bd125446d024a30373c9d
selection is ('I04D', 'I04E', 'I04F', 'I050', 'I051', 'I052', 'I053', 'I054', 'I055', 'I056', 'I057', 'I058', 'I059', 'I05A', 'I05B', 'I05C', 'I05D', 'I05E', 'I05F', 'I060', 'I061', 'I062', 'I063', 'I064', 'I065', 'I066', 'I067', 'I068', 'I069', 'I06A', 'I06B', 'I06C', 'I06D', 'I06E', 'I06F', 'I070', 'I071', 'I072', 'I073', 'I074', 'I075', 'I076', 'I077', 'I078', 'I079', 'I07A', 'I07B', 'I07C', 'I07D', 'I07E', 'I07F', 'I080', 'I081', 'I082', 'I083', 'I084', 'I085', 'I086', 'I087', 'I088', 'I089', 'I08A', 'I08B', 'I08C', 'I08D', 'I08E', 'I08F', 'I090', 'I091', 'I092', 'I093', 'I094', 'I095', 'I096', 'I097', 'I098', 'I099', 'I09A', 'I09B', 'I09C', 'I09D', 'I09E', 'I09F', 'I0A0', 'I0A1', 'I0A2', 'I0A3', 'I0A4', 'I0A5', 'I0A6', 'I0A7', 'I0A8', 'I0A9', 'I0AA', 'I0AB', 'I0AC', 'I0AD', 'I0AE', 'I0AF', 'I0B0', 'I0B1', 'I0B2', 'I0B3', 'I0B4', 'I0B5', 'I0B6', 'I0B7', 'I0B8', 'I0B9', 'I0BA', 'I0BB', 'I0BC', 'I0BD', 'I0BE', 'I0BF', 'I0C0', 'I0C1', 'I0C2', 'I0C3', 'I0C4', 'I0C5', 'I0C6', 'I0C7', 'I0C8', 'I0C9', 'I0CA')
first selection is I04D
values are ('C:\\WINDOWS\\Resources\\Themes\\Luna\\Shell\\NormalColor', 'shellstyle.dll', '361472', '23ecf1c97b1eb5d94a25dc677ec464e5')
checksum: 23ecf1c97b1eb5d94a25dc677ec464e5
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\MonitorSoft\MonitorSoft.py", line 213, in LoadSQL
CurFiles.execute('SELECT * FROM Files WHERE CheckSum = ?', (checksum,))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
This is the last two conclusions, at last, as you can see there is a bug.
To solve this, the very first step should be to print out all of your immediate values, so you can verify they are what you think they are. As a side effect, this makes your select statement much easier to read.
For example:
selection = WinRedactor.Table.selection()
print("selection is", selection)
first_selection = selection[0]
print("first selection is", first_selection)
values = WinRedactor.Table.item(first_selection, option='values')
print("values are", values)
checksum = values[3]
print("checksum:", checksum)
CurFiles.execute('SELECT * FROM Files WHERE CheckSum = ?', (checksum,))
My guess is, you'll be surprised at what you see. At the very least, you've have more data to put into your question so that we know precisely what the data is.

(python)(2.7.7) odd Syntax errors in code

from PIL import Image
import input_class
import input_function
import input_crop_values
import input_translate
class ImageChanger():
def __init__ ():
image_filename = input_class.input_file_name()
self.my_image = Image.open(image_filename)
chosen_Function = input_function.input_vaild_function()
if chosen_Function == "Crop" or chosen_Function == "crop":
crop_values = input_crop_values.input_crop_data()
my_image.crop(crop_values)
elif chosen_Function == "Translate" or chosen_function == "translate":
translate_values = input_translate.input_translate_data()
my_image.crop(translate_values)
else:
print("unexpected error while running code")
def printState():
print( "Your image file name is %s" % self.my_filename );
return (self.my_filename);
def translate(self,x_cord,y_cord):
return (self.my_image.offset(x_cord,y_cord));
def crop(self, box):
return (self.my_image.crop(box))
sorry for odd formatting,
Error:
Traceback (most recent call last):
File "C:\Users\Alexander\Desktop\Final_Udacity_project\dragon_picture_test.py", line 1, in <module>
import picture_changer
File "C:\Users\Alexander\Desktop\Final_Udacity_project\picture_changer.py", line 3, in <module>
import input_function
File "C:\Users\Alexander\Desktop\Final_Udacity_project\input_function.py", line 14
else
^
SyntaxError: invalid syntax
I have some other functions, not listed that use the input command sort of like a user interface, then it returns it to the larger class.
The places that the values are returned and what is return is:
line 8*: image_filename = input_class.input_file_name() # you would give a name of a picture here,
line 10*: chosen_function = input_function.input_vaild_function() # you Would give it either crop or translate can be sentence case or lowercase
line 11*: crop_values = input_crop_values.input_crop_data() # you would give it data in brackets like [1,2,3,4] and it would crop it.
line 15*: translate_values = input_translate.input_translate_data() # you would give it information in ( ), like (1,2,3,4) and it would translate it.
The code is acting really weird with the Boolean and the error message isn't helping me that much.
else, like other statements that come before a block, requires a colon.
else:

Categories