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()
Related
I have already searched for several solutions here and tried to get a working code. Everything works except for the where query.
In the where query I search for the highest value (numeric). However, this does not really work...
Here is my code and the structure of the MySQL database.
Thanks!
import pymysql
conn = pymysql.connect(host='localhost', unix_socket='', user='root', passwd='pw', db='database')
cur = conn.cursor()
cur.execute("SELECT * FROM dose")
for r in cur:
curr = conn.cursor()
sql = """UPDATE dose
SET status = "printed"
WHERE id = SELECT GREATEST (status) FROM dose (status);"""
# print(sql)
try:
# Execute the SQL command
curr.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
curr.close()
cur.close()
conn.close()
My SQL Database
You have a lot of things wrong in your code.
You don´t use the results of your first select query, and the only thing that you do is iterate over the results to execute an UPDATE
Your update query is wrong
You should change it to:
import pymysql
conn = pymysql.connect(host='localhost', unix_socket='', user='root', passwd='pw', db='database')
curr = conn.cursor()
sql = """UPDATE dose
SET status = 'printed'
WHERE id = (SELECT max(status) FROM dose) """
try:
# Execute the SQL command
curr.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
curr.close()
conn.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
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!
there are two mysql connection in my python script. example:
conn1 = mdb.connect(server, user, pw, db)
conn2 = mdb.connect(server, user, pw, db)
#1. then, I execute "select" sql command to select table A by conn1,
#2. after that, I execute "update" sql command to update table A by conn2,
#3. finally, I execute "select" sql command again to select table A by conn1,
but finally, the result of #3 is same as #1; however, after #2, i saw the data is updated in mysql workbench.
Is anybody know why #3 cannot get the latest data?
following is my python codes:
import MySQLdb as mdb
import time
conn1 = mdb.connect(SERVER, USER, PASSWORD, DB)
cur1 = conn.cursor()
count1 = cur.execute("SELECT trigger_time FROM trigger_set WHERE id=1")
data1 = cur.fetchall()
cur1.close()
print data1
conn2 = mdb.connect(SERVER, USER, PASSWORD, DB)
cur2 = conn2.cursor()
cur2.execute("update trigger_set set trigger_time = '2013/8/30 17:15' where id=1")
conn2.commit()
cur2.close()
cur1 = conn.cursor()
count1 = cur.execute("SELECT trigger_time FROM trigger_set WHERE id=1")
data1 = cur.fetchall()
print data1
Things would work if you commit your conn1 before selecting again.. or just enable auto_commit to True.
conn1.commit()
This has been talked about here: http://sourceforge.net/p/mysql-python/discussion/70461/thread/efea588e
BTW your code contains conn and cur variables which have not been defined..
I think the problem lies with reusing the same cursor `cur1' for step 1 and 3.Try using a different cursor or connection for your last select too.