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.
Related
I'm trying to create a database with the name a user will provide. As far as I know the correct way is to use the second argument of execute().
So I did as follows:
import psycopg2
conn = psycopg2.connect(host="...", dbname="...",
user="...", password="...", port='...')
cursor = conn.cursor()
query = ''' CREATE DATABASE %s ;'''
name = 'stackoverflow_example_db'
conn.autocommit = True
cursor.execute(query, (name,))
cursor.close()
conn.close()
And I got this error:
psycopg2.errors.SyntaxError: syntax error at or near "'stackoverflow_example_db'"
LINE 1: CREATE DATABASE 'stackoverflow_example_db' ;
I need to do this statement avoiding SQL injection, so using the second argument is a must.
You can't pass values as second argument of execute(), if the statement is a CREATE DATABASE one.
As pointed out by unutbu one way to approach this is using the psycopg2.sql submodule and use identifiers to build the statement avoiding SQL injection.
The code:
import psycopg2
from psycopg2 import sql
conn = psycopg2.connect(host="...", dbname="...",
user="...", password="...", port='...')
cursor = conn.cursor()
query = ''' CREATE DATABASE {} ;'''
name = 'stackoverflow_example_db'
conn.autocommit = True
cursor.execute(sql.SQL(query).format(
sql.Identifier(name)))
cursor.close()
conn.close()
Other aditional observations:
format() do not work with %s, use {} instead
Autocommit mode is a must for this statement to work
The specified connection user needs creation privileges
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)
I keep getting the error: "'builtin_function_or_method' object has no attribute 'execute'" I originally thought the complaint was on the table value function in SQL Server, however, I see that the message points to "execute", so I don't think refcur has execute defined. Here's what my connection string looks like:
conn = pyodbc.connect("Driver={SQL Server};"
"Server=myserver;"
"Database=mydatabase;"
"Trusted_Connection=yes;"
"autocommit=True;")
refcur = conn.cursor
sql = "exec myschema.mystoredproc #TVPobject=?"
refcur.execute(sql,this_object)
I've attached the image to show what I see in intellisense for what's available. Does anyone know why this is happening?
you aren't calling cursor, you're just returning a reference to that member function and storing it in refcur. In order to call it (and actually create a cursor), you need to add parenthesis:
refcur = conn.cursor()
# Here -------------^
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, ())
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.