I 've written two function for each table to receive field's command. And my teammate needs me to remix two function into one. Finally I make this function but it cannot receive my router table 's command.
this is my two functions:
# def readrouter(x):
# conn = sqlite3.connect('server.db')
# cur = conn.cursor()
# cur.execute("SELECT DISTINCT command FROM router WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",(x,))
# read = cur.fetchall()
# return read;
#
# a = input("x:")
# for result in readrouter(a):
# print (result[0])
# def readswitch(x):
# conn = sqlite3.connect('server.db')
# cur = conn.cursor()
# cur.execute("SELECT DISTINCT command FROM switch WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",(x,))
# read = cur.fetchall()
# return read;
# a = input("x:")
# for result in readrouter(a):
# print (result[0])
This is my function after combine two function into one:
def readciscodevice(x):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
if x:
cur.execute(
"SELECT DISTINCT command FROM switch WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(x,))
read = cur.fetchall()
return read
else:
cur.execute(
"SELECT DISTINCT command FROM router WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(x,))
read = cur.fetchall()
return read;
a = raw_input("x:")
for result in readciscodevice(a):
print(result[0])
I use my if-statement and it can read my switch table 's command but cannot get commands from switch table. Do I need to write boolean or something else to ensure that it can access my router table?
Update(I am trying to select two commands first which is enable and conf t, then I am going to identify my inputs,if the input is matched to my switch 's field "function", it provide some commands, ELSE going to match my router's field "function"):
# def readciscodevice(x):
# conn = sqlite3.connect('server.db')
# cur = conn.cursor()
#
# cur.execute(
# "SELECT DISTINCT command FROM switch WHERE function='configure terminal' or function='enable' ORDER BY key ASC"
# )
#
# if x:
# cur.execute(
# "SELECT DISTINCT command FROM switch WHERE function =? ORDER BY key ASC",
# (x,))
# read = cur.fetchall()
# return read
# else:
# cur.execute(
# "SELECT DISTINCT command FROM router WHERE function =? ORDER BY key ASC",
# (x,))
# read = cur.fetchall()
# return read;
#
#
# a = raw_input("x:")
# for result in readciscodevice(a):
# print(result[0])
In the updates code:
It cannot select enable conf t commands
Also cannot reach to my router 's field to get commands..
but it can select switch commands
You need to either introduce another argument to determine which block you wish to execute or have a clear distinction between two conditions of x.
'If x:' just checks that x has a valid (non falsey) value, so things with empty values will fail like: 0, None, false, '', etc.
Related
I am trying to update a row in an sql table based on results of a select query using python. How to add same so that if results found in select query we should be able to run update query and print as list updated, if not exit saying no result found to update table
cursor = conn.cursor()
cursor.execute(
"select * from student where email = 'xyz.com'"
)
student = cursor.fetchall()
print(student)
for row in student:
cursor.execute(" Update student set value = 0 where email = 'xyz.com'")
`
You don't need to do a separate SELECT, you can just use an OUTPUT clause to have your UPDATE statement return the value(s) from the row(s) that are updated. For example, with pyodbc:
sql = """\
UPDATE student SET value = 0
OUTPUT INSERTED.student_number
WHERE email = 'xyz.com' AND (value <> 0 OR value IS NULL)
"""
student_numbers = crsr.execute(sql).fetchall()
print(student_numbers) # [(1001, ), (1003, )]
I have made a GUI in PyQt5 that allows you to deal with a database. There is an insert button which allows you to insert data into a database and then using a stored procedure whose parameter is a MySQL query in string format, it passes a select query to the stored procedure whose where clause consists of values just entered.
`
def insert(self):
try:
self.table.setRowCount(0)
QEmpID = self.lineEmpID.text() + "%"
QFName = self.lineFName.text() + "%"
QLName = self.lineLName .text() + "%"
QSalary = self.lineSalary.text() + "%"
QTask = self.lineTask.text() + "%"
mydb = mc.connect(host="localhost",username="root",password="",database="Office")
mycursor = mydb.cursor()
selectQuery = "SELECT * From Employee WHERE EmpID like '{}' and FirstName like '{}' and LastName like '{}' and Salary like '{}' and Task like '{}'".format(QEmpID, QFName,QLName,QSalary,QTask)
QEmpID = self.lineEmpID.text()
QFName = self.lineFName.text()
QLName = self.lineLName.text()
QSalary = self.lineSalary.text()
QTask = self.lineTask.text()
insertQuery = "INSERT INTO Employee Values({},'{}','{}',{},'{}')".format(QEmpID,QFName, QLName, QSalary, QTask)
mycursor.execute(insertQuery)
mydb.commit()
insertResult = mycursor.fetchall()
mycursor.callProc('fetchData',[selectQuery])
for result in mycursor.stored_results():
selectResult = result.fetchall()
for row_number,row_data in enumerate(selectResult):
self.table.insertRow(row_number)
for column_number,data in enumerate(row_data):
self.table.setItem(row_number,column_number,QTableWidgetItem(str(data)))
except mc.Error as e:
print(e)
The above is my python code for the insert function which is then connected to the insert button.
`
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `fetchData`(in query1 varchar(1000))
begin
set #q = query1;
PREPARE stmt from #q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end$$
DELIMITER ;
The above is my stored procedure which executes a query passed to it in string format.
However, when I type in the record to be inserted into the fields and then press Insert, the following shows up without any tracebacks or error reports in the IDLE Shell:
The thing is, the record does get inserted into the database and I think the issue is with the calling of stored procedure with a select query passed to it and whose result can then be populated into the QTableWidget.
I can't think of anything right now. Help is needed.
Thank you!
I currently have a list of id's approx. of size 10,000. I need to update all rows in the mySQL table which have an id in the inactive_ids list that you see below. I need to change their active status to 'No' which is a column in the mySQL table.
I am using mysql.connector python library.
When I run the code below, it is taking about 0.7 seconds to execute each iteration in the for loop. Thats about a 2 hour run time for all 10,000 id's to be changed. Is there a more optimal/quicker way to do this?
# inactive_ids are unique strings something like shown below
# inactive_ids = ['a9okeoko', 'sdfhreaa', 'xsdfasy', ..., 'asdfad']
# initialize connection
mydb = mysql.connector.connect(
user="REMOVED",
password="REMOVED",
host="REMOVED",
database="REMOVED"
)
# initialize cursor
mycursor = mydb.cursor(buffered=True)
# Function to execute multiple lines
def alter(state, msg, count):
result = mycursor.execute(state, multi=True)
result.send(None)
print(str(count), ': ', msg, result)
count += 1
return count
# Try to execute, throw exception if fails
try:
count = 0
for Id in inactive_ids:
# SAVE THE QUERY AS STRING
sql_update = "UPDATE test_table SET Active = 'No' WHERE NoticeId = '" + Id + "'"
# ALTER
count = alter(sql_update, "done", count)
# commits all changes to the database
mydb.commit()
except Exception as e:
mydb.rollback()
raise e
Do it with a single query that uses IN (...) instead of multiple queries.
placeholders = ','.join(['%s'] * len(inactive_ids))
sql_update = f"""
UPDATE test_table
SET Active = 'No'
WHERE NoticeId IN ({placeholders})
"""
mycursor.execute(sql_update, inactive_ids)
in my python code I insert a value into a table.
In the table, there is a sequence which automatically assigns an ID.
After the insert, I want to get this it back in to my python application:
import cx_Oracle, sys
with cx_Oracle.connect(user=ORA_USER,password=ORA_PWD,dsn=ORA_DSN) as conn:
with conn.cursor() as cur:
cur.execute("Insert into my_table columns(data) values ('Hello')")
conn.commit()
with cx_Oracle.connect(user=ORA_USER,password=ORA_PWD,dsn=ORA_DSN) as conn:
with conn.cursor() as cur:
r = cur.execute("select id from my_table where data = 'Hello'")
print(r)
if r is None:
print("Cannot retrieve ID")
sys.exit()
Unfortunately, the result set r is always "None" even though the value has been inserted properly (checked via sqldeveloper).
What am I doing wrong?
I even open a new connection to be sure to grab the value...
After calling execute() for a SELECT statement you need to call fetchone(), fetchmany() or fetchall() as shown in the cx_Oracle documentation SQL Queries.
Or you can use an iterator:
with connection.cursor() as cursor:
try:
sql = """select systimestamp from dual"""
for r in cursor.execute(sql):
print(r)
sql = """select 123 from dual"""
(c_id,) = cursor.execute(sql).fetchone()
print(c_id)
except oracledb.Error as e:
error, = e.args
print(sql)
print('*'.rjust(error.offset+1, ' '))
print(error.message)
However to get an automatically generated ID returned without the overhead of an additional SELECT, you can change the INSERT statement to use a RETURNING INTO clause. There is an example in the cx_Oracle documentation DML RETURNING Bind Variables that shows an UPDATE. You can use similar syntax with INSERT.
With the table:
CREATE TABLE mytable
(myid NUMBER(11) GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH 1),
mydata VARCHAR2(20));
You can insert and get the generated key like:
myidvar = cursor.var(int)
sql = "INSERT INTO mytable (mydata) VALUES ('abc') RETURNING myid INTO :bv"
cursor.execute(sql, bv=myidvar)
i, = myidvar.getvalue()
print(i)
If you just want a unique identifier you get the ROWID of an inserted row without needing a bind variable. Simple access cursor.lastrowid after executing an INSERT.
I am trying to return some commands to my partner in sqlite3 db in python.
As my partner needs me to write a function to return command, I need some idea from the logic to write the function.
First I write the thing that maybe useless.
def readrouter():
function = "SELECT command FROM switch WHERE type = ? or function = ? ORDER BY key ASC"
conn = sqlite3.connect('server.db')
cur = conn.cursor()
print(read)
conn.commit()
I have learned that now I am trying to connect to server but it can't return my variable function and print it out.
Should I make parameter for the function and how should I write it?
thanks for help and now i fix it with:
def readswitch(function,read):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
function = "SELECT command FROM switch WHERE type = ? or function = ? ORDER BY key ASC"
cur.execute(function)
read = cur.fetchone()
for row in read:
print(read)
conn.commit()
is there any mistake and def readswitch(function,read): shows that the function and read [Parameter 'function' value is not used]
where is my mistake?
# Paul Rooney
for the meaning of the function
function = "SELECT command FROM switch WHERE type = ? or function = ? ORDER BY key ASC"
is to select some kinds of commands by different function
for example:
My partner want to select a vlan command
then i will search the function which is "create vlan"
and the usage of type is to provide some command which is global use (enable, conf t)
For the command , i will print out:
('enable',)
('configure terminal',)
('vlan (number)',)
('name (vlan name)',)
now , should i make two variables to fill in the "?"
like:
function = "SELECT command FROM switch WHERE type = " +x+" or function = " +y+ " ORDER BY key ASC"
In the Parameterized queries http://zetcode.com/db/sqlitepythontutorial/
I do not know what is the meaning of uId = 1 and i change it to x=1
what will be happen?
now i correct it like:
def readswitch(function,read):
x=1
#
conn = sqlite3.connect('server.db')
cur = conn.cursor()
function = "SELECT command FROM switch WHERE function =:function ORDER BY key ASC",{"function":x}
con.commit()
cur.execute(function)
read = cur.fetchone()
for row in read:
print read.row[0], row[1]