sqlite attribute execute is read-only - python

I am using sqlite to create and connect to a sqlite db foo.db
When I try to do an insert into the DB. I get the following AttributeError
AttributeError: 'sqlite3.Cursor' object attribute 'execute' is read-only
I can't seem to find any information on this error. Does anyone have any idea what this exception means?
I am using python 2.7 with virtualenv.
The following is the code I am trying to execute assume date is a string.
username = 'user'
pwdhash = some_hash_function()
email = 'user#foo.com'
date = '11/07/2011'
g.db = sqlite3.connect('foo.db')
cur = g.db.cursor()
cur.execute = ('insert into user_reg (username,pwdhash,email,initial_date)\
values (?,?,?,?)',
[username,
pwdhash,
email,
date])
g.db.commit()
g.db.close()
Thanks

You're trying to modify an attribute of the cursor. You want to call a method of the cursor.
It should be
cur.execute('insert into user_reg (username,pwdhash,email,initial_date)\
values (?,?,?,?)',
[username,
pwdhash,
email,
date])
Not
cur.execute = ('insert ...

Seems to be a simple syntax error.
You are trying to set a value to the command execute while you have just to call it:
remove the '=' and it should be fine.

Related

MySQL python connector: "not all arguments converted during bytes formatting"

I have a mysql database in which 'user' table having f_name,l_name,password email(pk) by which session is created and table 'friendgroup' having fg_name(pk), email((pk),users.email(FK)) and table 'member' having email(pk,user.email(fk)), owner_email(pk,friendgroup.email(fk)), fg_name(pk,friendgroup.fg_name(fk)), and a python flask file below.
After login account, I wish to add a friend in chat. I tried to fix it from session['email']
def add_friend():
user = session['email']
friendgroups = _get_own_friendgroups(user) return
render_template('addFriend.html', friendgroups=friendgroups)
def _get_own_friendgroups(user):
cursor = mysql.connection.cursor()
#find all friendgroups that the user owns
find_owned_friendgroups = 'SELECT fg_name, description FROM friendgroup WHERE owner_email = %s ORDER BY fg_name ASC'
cursor.execute(find_owned_friendgroups, (user))
owned_friendgroups = cursor.fetchall()
cursor.close()
return owned_friendgroups
I expect output will be an open window and actively use of add friend when needed but showing error:
MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting
A common error in python is to use (bar) instead of (bar,) the former not being a tuple.
Try with:
cursor.execute(find_owned_friendgroups, (user,))

can't see table created by pyodbc in ms access

I am accessing a MS Access Database in Python 3.6 using pyodbc library. I can read a table, no problems. The I created a simple table (Employee). I inserted records. I was able to fetch the records too by reading the table, no problems.
I also listed the tables in the MS Access DB. Employee table shows in the list.
But when I open up the MS Access Database, I do not find the table. I changed MS Access DB to show hidden and system objects. Employee table doesn't show up.
What am I doing wrong?
Thanks
Here is the code:
import pyodbc
db_file = r'''C:\TickData2018\StooqDataAnalysis.accdb'''
user = 'admin'
password = ''
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.accdb)};DBQ=%s;UID=%s;PWD=%s' %\
(db_file, user, password)
# Or, for newer versions of the Access drivers:
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;UID=%s;PWD=%s' %\
(db_file, user, password)
conn = pyodbc.connect(odbc_conn_str)
print("connection made")
c = conn.cursor()
c.execute("SELECT * FROM 5MtsBaseForAnalysisSorted")
list1 = c.fetchmany(2)
print(list1[0][0])
print(list1[0][1])
print(list1[0][2])
try:
c.execute("""CREATE TABLE employee(
first text,
last text,
pay integer
);""")
except Exception as e:
print(e)
conn.commit
c.execute("INSERT INTO employee VALUES ('Krishna', 'Sundar', 50000)")
c.execute("INSERT INTO employee VALUES ('Divya', 'Sundar', 70000)")
c.execute("INSERT INTO employee VALUES ('Panka', 'Sundar', 70000)")
conn.commit
c.execute("SELECT * FROM employee")
print(c.fetchall())
c.tables()
rows = c.fetchall()
for row in rows:
print(row)
c.close()
del c
conn.close()
This is a general Python object model where you need to call the actual function and not its bounded name. Specifically, your commit lines are not correct where
conn.commit
Should be with open/close parentheses:
conn.commit()
Another way to see the difference is by reviewing the object's type:
type(conn.commit)
# <built-in method commit of pyodbc.Connection object at 0x000000000B772E40>
type(conn.commit())
# NoneType
I did reproduce your issue with exact code and adding parentheses resolved the issue.
An additional solution to manually committing is to set autocommit = True when the connection instance is created.
Eg:
conn = pyodbc.connect(odbc_conn_str, autocommit = True)

SQL Select where not working

I am using Python/Flask and trying to query my DB.
conn = sqlite3.connect('./flaskdb.db')
cur = conn.cursor()
cur.execute('SELECT email FROM users WHERE email=\'%s\'', "name")
I have 2 columns, email, password and the value name, password as one of the row/entries.
Why isn't this working? I get the error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 7 supplied.
I think you are getting bogged down with using prepared statements here. Try this code:
conn = sqlite3.connect('./flaskdb.db')
cur = conn.cursor()
name = 'someone#somewhere.com'
cur.execute('SELECT email FROM users WHERE email=?', (name,))
Corrections include using ? as a placeholder instead of %s, the latter which is what might be used for other databases. Also, if you want to bind a variable called name, then it too should not have quotes around it.
I have a solution:
cur.execute('SELECT password FROM users WHERE email=(?)', (email,))
you need it as a tuple and (?) as a placeholder.

Python - MySQL SELECT query with dynamic table name

I am trying to fetch all the rows from the MySQL DB in Python. How to fetch all row from the table, when the table name is variable?
Here is a method that I wrote, however I am getting error while running it.
def get_rows(self, table_name):
cursor = self.conn.cursor()
query = ("SELECT * "
"FROM %s ")
try:
cursor.execute(query, (table_name,))
value = cursor.fetchall()
finally:
cursor.close()
return value
And I am getting the following error:
AttributeError: 'NoneType' object has no attribute 'cursor'
I tried the similar way in WHERE clause and it worked fine.
You have a problem with conn object.
'NoneType' object has no attribute 'cursor' means conn is None, probably because it wasn't established during the __ init __ call.
You can't dynamically bind object names (here you're attempting to bind a table name) or syntactic constructs to a query. If you wish to have such a behavior you'd have to resort to string manipulation, meaning you're forfeiting all the security advantages prepared statements offer:
query = ("SELECT * FROM %s" % table_name)
try:
cursor.execute(query, ())

Python sqlite3 cursor has no attribute commit

When I run this code:
path = '~/Scripts/wallpapers/single.png'
conn = sqlite3.connect('/Users/Heaven/Library/Application Support/Dock/desktoppicture.db')
cur = conn.cursor();
cur.execute("insert into data values ('" + path + "');")
cur.commit()
I receive the following error
AttributeError: 'sqlite3.Cursor' object has no attribute 'commit'
and I have absolutely no idea why.
commit() is a member method of sqlite3.Connection not sqlite3.Cursor. Here it is in the docs.
From the answer from sir_charles804 (sorry not enough points to add this as comment) follows it should be:
conn.commit()
instead of
cur.commit()
It's
conn.commit()
conn.close() //if you intend to close it afterwards
Explanation:
The cursor is only used to pass instructions to sqlite, while you have to commit or close with the instance you've made to connect to your database.

Categories