I found such a code online but I am trying to edit it to link Python data to postgresql. I am really new to coding so I would really appreciate your help.
import psycopg2
import sys
connection = None
connection = psycopg2.connect("host='localhost' db='football'
user ='postgres' password='password'")
cur = con.cursor()
con.commit()
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `Games` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster#python.org', 'very-secret'))
except SyntaxError as e:
print("There was an error: {}".format(e))
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT row[5]"
cursor.execute(sql, ('row [5]',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
Your try statement needs to be paired with an except. The purpose of try/except is to catch any errors thrown in your try block gracefully. But without an except, try isn't very useful.
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `Games` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster#python.org', 'very-secret'))
except SyntaxError as e:
print("There was an error: {}".format(str(e)))
Your actual psycopg2 code looks about right.
Related
I can't establish connection to my Databases because I'm apparently missing an SQL statement, but I don't know where it is. Pls Help.
import mysql.connector as msql
from mysql.connector import Error
import pandas as pd
db123 = msql.connect(host='localhost', port='7616', user='root', password='admin#123')#give ur username, password
empdata = pd.read_csv('C:\\Users\\me\\Desktop\\Goods.csv', index_col=False, delimiter=',', low_memory=False)
empdata.head()
try:
if db123.is_connected():
cursor = db123.cursor()
for i,row in empdata.iterrows():
sql = """INSERT INTO mynewsystem.products(Barcode, Prod_Name, Price) VALUES (%s,%s,%s)"""
cursor.execute(sql, tuple(row))
print("Record inserted")
db123.commit()
except Error as e:
print("Error while connecting to MySQL", e)
Inserting records into a MySQL database using Python MySQL Connector. Process works around 98% of the time. I am getting intermittent timeout responses from the server. Other times the script just hangs and nothing happens, which is the worse possible situation.
Can I timeout/kill the process using threading?
Can I set a timeout on the execute or commit statement?
import mysql.connector
try:
mydb = mysql.connector.connect(host="...", user="...", password="...", database="...")
mycursor = mydb.cursor()
except Exception as e:
print(e)
#Seems to always work up to this point
sql = "INSERT INTO test (name,tagline,location,experience) VALUES (%s, %s, %s, %s)"
val = ('test', 'test', 'test', 'test')
try:
mycursor.execute(sql, val)
mydb.commit()
except Exception as e:
print(e)
mycursor.close()
mydb.close()
I have uploaded a jpg image with the bytes() function to the bytea field.
INSERT CODE
conn = None
try:
# read data from a picture
imagen = open("imagen.jpg", "rb").read()
# connect to the PostgresQL database
conn = psycopg2.connect(host="localhost", database="test", user="postgres", password="admin")
# create a new cursor object
cur = conn.cursor()
# execute the INSERT statement
cur.execute("INSERT INTO nuevotest(id,data) " +
"VALUES(%s,%s)",
(1, bytes(imagen)))
# commit the changes to the database
conn.commit()
# close the communication with the PostgresQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
SELECT CODE:
conn = None
try:
conn = psycopg2.connect(host="localhost", database="test", user="postgres", password="admin")
# create a new cursor object
cur = conn.cursor()
# execute the INSERT statement
cur.execute(""" SELECT data
FROM nuevotest
WHERE id=1 """,
)
# commit the changes to the database
conn.commit()
imagen = cur.fetchall()
print(type(imagen))
print(imagen)
# close the communication with the PostgresQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
But what i was expectiong was a list or tuple with the byte code, not this:
PyCharm console with a (memory direction? idk)
I have no idea how to work with that.
Depends on what you are planning on doing after you retrieve the data. As #adrian_klaver said, you can use a buffer to write the output. Like this you would send it to a file:
with open(your_output_file, 'wb') as im:
im.write(the_in_memory_data)
Using PIL you can output it to the image viewer of the system without saving it.
I want to insert data into my database, but how can the id auto increment in python?
In PHP, we only do this by using DEFAULT like this query and data inserted:
mysqli_query($connection, "INSERT INTO setting VALUE(DEFAULT,'$name','$address')");
How can i do it in PYTHON MYSQL?
def insertSetting(name,address):
try:
connection = mysql.connector.connect(host='localhost', database='myDB', user='root', password='')
cursor = connection.cursor()
query = """INSERT INTO setting (id_setting, name, address) VALUES (DEFAULT, %s, %s) """
records =(name,address)
cursor.executemany(query,records)
connection.commit()
print("Inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
insertSetting(name,address)
I got error :
Failed to insert into MySQL table Failed processing format-parameters;
'int' object is not iterable
i expect the result :
The id auto increment in database
remove your column id_settings during insert since its auto increment.
query = """INSERT INTO setting (name, address) VALUES (%s, %s) """
for a project at uni i need to insert different kinds of variables into a MySql Database. Connecting and Inserting the data so far works fine. I don't know how to handle potential errors though. Which potential mistakes and exceptions do i need to catch and take care of ?
In my code i used a main method to just test the program. In the final version just the connection and the SQL queries are copied into the main script. I am open to use either the MySQL or the mysql.connector. Also: Do i need to put the query into a try block aswell ? Here is my code so far:
import mysql.connector
import time
from mysql.connector import errorcode
try:
con = mysql.connector.connect(
user= 'root',
password= '',
host='localhost',
database= 'testdb')
print("Connected.")
cursor = con.cursor()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Passwort // Username")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("DataBase does not exist")
else:
print(e)
def insert_temp(Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID):
query = "INSERT INTO Temperatur (Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID)" \
"VALUES(%s, %s, %s, %s)"
args= (Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID)
cursor.execute(query, args)
con.commit()
def main():
# just test values so far
value = 18.5;
insert_temp(' ', time.strftime('%Y-%m-%d %H:%M:%S'), value, '1');
cursor.close()
con.close()
if __name__ == '__main__':
main()
please note that i have very little experience in python programming