When using sqlite3 for python, how do I determine if a row has been successfully inserted into a table? e.g.
conn = sqlite3.connect("test.db")
c = conn.cursor()
c.execute("INSERT INTO TEST VALUES ('sample text')")
c.commit()
c.close()
If no exception was thrown when calling execute() or commit(), it was inserted when you called commit().
Committing a transaction successfully is a guarantee from the database layer that the insert was written to disk.
you can get all the rows and see if its in there with:
SELECT * FROM TEST
But SQLite will give you an error message if it didnt work.
you can count() rows before inserting and after inserting.
You could try something like this to have an error message:
try:
c.execute("INSERT INTO TEST VALUES ('sample text')")
except sqlite3.OperationalError, msg:
print msg
You should do the commit on connection made(db selected which is conn) not on cursor.
conn = sqlite3.connect("test.db")
c = conn.cursor()
c.execute("INSERT INTO TEST VALUES ('sample text')")
#commit the changes to db
conn.commit()
conn.close()
First You should do the commit on the connection object not the cursor i.e
conn.commit() not c.commit()
Then you can examine lastrowid on the cursor to determine if the insert was successful after conn.commit()
c.lastrowid
Related
I can not figure out why I can not get my cursor.execute statement to work. I do not get any Python errors however the code continues to fail the try command. I am connected to SQL and I can print a list of column in the table. Here is my code.
import pyodbc
# Connect to the database
connection = pyodbc.connect(
r'DRIVER={SQL Server};'
r'SERVER=******;'
r'DATABASE=****;'
r'UID=****;'
r'PWD=*****'
)
try:
# Create a cursor
cursor = connection.cursor()
# Execute a SQL statement
cursor.execute("INSERT INTO employee table (FName, SSN) VALUES (?, ?)", "john", "123-123-1234")
connection.commit()
print("success")
except pyodbc.Error:
print("error")
connection.rollback()
# Close the cursor and connection
cursor.close()
connection.close()
I get a 42000 error when I print out the error but the syntax looks to be all correct.
cursor.execute("INSERT INTO employee table (FName, SSN) VALUES (?, ?)", "john", "123-123-1234")
I see two problems here.
First, the syntax for INSERT should look like this:
INSERT INTO tablename (column1, column2) VALUES (value1, value2)
But instead of tablename, you have employee table. If employee is the name of the table, then just use that; you don't need the extra word table hanging out there.
Second, you're passing two arguments "john", "123-123-1234" to the execute function, but this is wrong. It should be one argument, which is a list/tuple containing all the desired values, like so:
cursor.execute("...", ("john", "123-123-1234"))
I don't run into any error messages anymore but when i refresh my database nothing is actually injected? using psycopg2 and pgadmin4
import psycopg2 as p
con = p.connect("dbname =Feedbacklamp user =postgres password= fillpw host=localhost port=5432")
cur = con.cursor()
sql = "INSERT INTO audiolevels(lokaalnummer,audiolevel,tijdstip) VALUES (%s,%s,%s)"
val = "100"
val1 = 100
val2 = "tijdstip"
cur.execute(sql,(val,val1,val2))
con.commit
cur.close
con.close
The values to be inserted into my pgadmin sql database
con.commit() should be a function call I think is your problem. You are missing the parentheses which treats it as member access instead of a function call. This also goes for the other methods cur.close() and con.close()
I am creating a Python app that will store my homework in a database (using PhpMyAdmin). Here comes my problem:
At this moment, I am sorting every input with an ID (1, 2, 3, 4...), a date (23/06/2018...), and a task (read one chapter of a book). Now I would like to sort them by the date because when I want to read what do I have to do. I would prefer to see what shall I do first, depending on when should I get it done. For example:
If I have two tasks: one 25/07/2018 and the other 11/07/2018, I would like to show the 11/07/2018 first, no matter if it was addead later than the 25/07/2018. I am using Python (3.6), pymysql and PhpMyAdmin to manage the database.
I have had an idea to get this working, maybe I could run a Python script every 2 hours, that sorts all the elements in the database, but I have no clue about how can I do it.
Now, I will show you the code that enters the values into a database and then it shows them all.
def dba():
connection = pymysql.connect(host='localhost',
user='root',
password='Adminhost123..',
db='deuresc',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `deures` (`data`, `tasca`) VALUES (%s, %s)"
cursor.execute(sql, (data, tasca))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `deures` WHERE `data`=%s"
cursor.execute(sql, (data,))
resultat = cursor.fetchone()
print('Has introduït: ' + str(resultat))
finally:
connection.close()
def dbb():
connection = pymysql.connect(host='localhost',
user='root',
password='Adminhost123..',
db='deuresc',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `deures`"
cursor.execute(sql)
resultat = cursor.fetchall()
for i in resultat:
print(i)
finally:
connection.close()
Can someone help?
You don't sort the database. You sort the results of the query when you ask for data. So in your dbb function you should do:
SELECT * FROM `deures` ORDER BY `data`
assuming that data is the field with the date.
try:
conn = psycopg2.connect("dbname='test1' user='postgres' host='localhost' password='123'")
cur = conn.cursor()
cur.execute("""INSERT INTO product_info (product_name) VALUES (%s)""", 'xxx')
except:
print "error happens"
The above is my code snippet, I have no trouble connecting to the database, but I have some problem inserting the value into it.
I execute the same query in postgres and it works, so i think it's a syntax problem.
Can someone show me what is the right way to do insertion?
cur.execute("""
insert into product_info (product_name) VALUES (%s)
""", ('xxx',))
conn.commit()
Notice that the value is passed to the method wrapped in an iterable.
I have been trying to insert data into the database using the following code in python:
import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()
The code runs without any errors. But no updation to the database takes place. I tried adding the conn.commit() but it gives an error saying module not found. Please help?
You do have to commit after inserting:
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()
or use the connection as a context manager:
with conn:
cursor.execute("Insert into links (link,id) values (?,?)", (a, b))
or set autocommit correctly by setting the isolation_level keyword parameter to the connect() method to None:
conn = db.connect('insertlinks.db', isolation_level=None)
See Controlling Transactions.
It can be a bit late but set the autocommit = true save my time! especially if you have a script to run some bulk action as update/insert/delete...
Reference: https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level
it is the way I usually have in my scripts:
def get_connection():
conn = sqlite3.connect('../db.sqlite3', isolation_level=None)
cursor = conn.cursor()
return conn, cursor
def get_jobs():
conn, cursor = get_connection()
if conn is None:
raise DatabaseError("Could not get connection")
I hope it helps you!