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]
Related
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!
Can someone help me understand what's incomplete about my code, no matter what I try I keep getting the sqlite3.OperationalError: incomplete input. My code is
editor = Tk()
editor.title('Edit Record')
editor.geometry('400x400')
#Creating database
conn = sqlite3.connect('Student_info.db')
c = conn.cursor()
record_id = delete_box.get()
#Query the database
c.execute("SELECT * FROM Student_info WHERE oid ="+(record_id))<-----
records = c.fetchall()
The line that sublime is referring to is the one I've drawn an arrow to, if anyone could help that would be great!
Your syntax for execute() is off. You should be using a prepared statement as the first parameter, followed by a tuple of parameters as the second function parameter:
record_id = delete_box.get()
c.execute("SELECT * FROM Student_info WHERE oid = %s", (record_id,))
records = c.fetchall()
I had a question pertaining to mysql as being used in Python. Basically I have a dropdown menu on a webpage using flask, that provides the parameters to change the mysql queries. Here is a code snippet of my problem.
select = request.form.get('option')
select_2 = request.form.get('option_2')
conn = mysql.connect()
cursor = conn.cursor()
query = "SELECT * FROM tbl_user WHERE %s = %s;"
cursor.execute(query, (select, select_2))
data = cursor.fetchall()
This returns no data from the query because there are single qoutes around the first variable, i.e.
Select * from tbl_user where 'user_name' = 'Adam'
versus
Select * from tbl_user where user_name = 'Adam'.
Could someone explain how to remove these single qoutes around the columns for me? When I hard code the columns I want to use, it gives me back my desired data but when I try to do it this way, it merely returns []. Any help is appreciated.
I have a working solution dealing with pymysql, which is to rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string. maybe you can try in a similar way, check this:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()
I have been using Psycopg2 to read stored procedures from Postgres successfully and getting a nice tuple returned, which has been easy to deal with. For example...
def authenticate(user, password):
conn = psycopg2.connect("dbname=MyDB host=localhost port=5433 user=postgres password=mypwd")
cur = conn.cursor()
retrieved_pwd = None
retrieved_userid = None
retrieved_user = None
retrieved_teamname = None
cur.execute("""
select "email", "password", "userid", "teamname"
from "RegisteredUsers"
where "email" = '%s'
""" % user)
for row in cur:
print row
The row that prints would give me ('user#gmail.com ', '84894531656894hashedpassword5161651165 ', 36, 'test ')
However, when I run the following code to read a row of fixtures with a Stored Procedure, I get (what looks to me like) an unholy mess.
def get_from_sql(userid):
conn = psycopg2.connect("dbname=MyDB host=localhost port=5433 user=postgres password=pwd")
fixture_cursor = conn.cursor()
callproc_params = [userid]
fixture_cursor.execute("select sppresentedfixtures(%s)", callproc_params)
for row in fixture_cursor:
print row
The resulting output:
('(5,"2015-08-28 21:00:00","2015-08-20 08:00:00","2015-08-25 17:00:00","Team ",,"Team ",,"Final ")',)
I have researched the cursor class and cannot understand why it outputs like this for a stored procedure. When executing within Postgres, the output is in a perfect Tuple. Using Psycopg2 adds onto the tuple and I don't understand why?
How do I change this so I get a tidy tuple? What am I not understanding about the request that I am making that gives me this result?
I have tried the callproc function and get an equally unhelpful output. Any thoughts on this would be great.
This is because you're SELECTing the result of the function directly. Your function returns a set of things, and each "thing" happens to be a tuple, so you're getting a list of stringified tuples back. What you want is this:
SELECT * FROM sppresentedfixtures(...)
But this doesn't work, because you'll get the error:
ERROR: a column definition list is required for functions returning "record"
The solution is to return a table instead:
CREATE OR REPLACE FUNCTION sppresentedfixtures(useridentity integer) RETURNS TABLE(
Fixture_No int,
Fixture_Date timestamp,
...
) AS
$BODY$
select
"Fixtures"."Fixture_No",
"Fixtures"."Fixture_Date",
...
from "Fixtures" ...
$BODY$ LANGUAGE sql
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.