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.
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.
I'm having some troubles with this python method.
I don't have any problem getting the select results but when I've tried to execute the update I don't get any results.
I have tried to generate another cursor object, redefine the cursor, generate another connection, use a different sql query (without the use of the %s) and I didn't have any results.
If you could give me any help i would be really appreciate.
def getTarea():
conn = db.connect('url','user','pass','dbInstance')
with conn:
try:
cursor = conn.cursor(db.cursors.DictCursor)
sql = "SELECT CMD, ID_TAREA FROM TAREAS WHERE OBTENIDA = '0' AND DEVICE_ID = '1001' ORDER BY FECHA_TAREA DESC LIMIT 1"
cursor.execute(sql)
f.write(sql+"\n")
# fetch all of the rows from the query
data = cursor.fetchone()
# print the rows
f.write("CMD: "+data["CMD"]+"\n")
f.write("ID_TAREA: "+ str(data["ID_TAREA"])+"\n")
idTarea = str(data["ID_TAREA"])
obtenido = 1
cursor.execute("""UPDATE TAREAS SET OBTENIDA=%s WHERE ID_TAREA =%s""", (obtenido, idTarea))
cursor.close()
conn.close()
except Exception as e:
f.write("error \n"+e)
return cmd
conn.commit() will commit the changes, as documented in this similar post: Database does not update automatically with MySQL and Python
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