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.
Related
I am trying to create a database file using the following code:
def dbconnect():
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
sqlite_select_Query = "select sqlite_version();"
cursor.execute(sqlite_select_Query)
record = cursor.fetchall()
print("SQLite Database Version is: ", record)
cursor.close()
except sqlite3.Error as error:
print("Error while connecting to sqlite", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
conn = dbconnect()
conn.close()
yet when I run the code, although there are no file errors, it doesnt print anything or create a SQL file in the folder of the python code.
I can't seem to figure out what is going wrong.
This question already has answers here:
psycopg2 not actually inserting data
(2 answers)
Closed 2 months ago.
I am running this python code to read in quotes from a file and then insert each quote into a table in my database. When I run the script in my terminal there are no errors but when I go to the database table I tried to insert to it tells me there are 0 rows.
#!/usr/bin/python
import psycopg2
import re
from config import config
conn = psycopg2.connect(
host="localhost",
database="favorite_quotes",
user="postgres",
password="???")
data = None
with open('file.txt', 'r') as file:
data = file.read()
list_of_strings = re.findall('“(.+?)” \(.+?\)', data, re.DOTALL)
def insert_quotes():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
for str in list_of_strings:
cur.execute("INSERT INTO the_courage_to_be_disliked (quote) VALUES (%s)", [str])
# execute a statement
# dblist = list(cur.fetchone())
# quotes = []
# for row in cur:
# quotes.append(row[1])
# return quotes
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
insert_quotes()
You aren't committing your inserts, so they won't be visible from outside the current connection, and will be implicitly rolled back when the connection is closed.
TL;DR, add a call to conn.comimt() before calling conn.close().
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.
i have to connect to mysql server and grab some data for ever
so i have two way
1)connect to mysql the grab data in a while
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
while True:
cursor.execute("statments")
sqlData = cursor.fetchone()
print(sqlData)
sleep(0.5)
this working good but if script crashed due to mysql connection problem script goes down
2)connect to mysql in while
while True:
try:
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
cursor.execute("statments")
sqlData = cursor.fetchone()
print(sqlData)
cursor.close()
conn.close()
sleep(0.5)
except:
print("recoverable error..")
both code working good but my question is which is better?!
Among these two, better way will be to use a single connection but create a new cursor for each statement because creation of new connection takes time but creating a new cursor is fast. You may update the code as:
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
while True:
try:
cursor = conn.cursor(buffered=True)
cursor.execute("statments")
sqlData = cursor.fetchone()
print(sqlData)
except Exception: # Catch exception which will be raise in connection loss
conn = mysql.connector.connect(user='root',password='password',host='localhost',database='db',charset='utf8',autocommit=True)
cursor = conn.cursor(buffered=True)
finally:
cursor.close()
conn.close() # Close the connection
Also read Defining Clean-up Actions regarding the usage of try:finally block.
I am trying to make a login system with python and mysql. I connected to the database, but when I try to insert values into a table, it fails. I'm not sure what's wrong. I am using python 3.5 and the PyMySQL module.
#!python3
import pymysql, sys, time
try:
print('Connecting.....')
time.sleep(1.66)
conn = pymysql.connect(user='root', passwd='root', host='127.0.0.1', port=3306, database='MySQL')
print('Connection suceeded!')
except:
print('Connection failed.')
sys.exit('Error.')
cursor = conn.cursor()
sql = "INSERT INTO login(USER, PASS) VALUES('test', 'val')"
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
print('Operation failed.')
conn.close()
I think it may have to do with the order of the statements in the connection. According to the PyMySQL github (found here) the correct order is host, port, user, passwd, db.
Like this :
user = input("User: ")
pass = input("Pass: ")
sql = "INSERT INTO login(USER, PASS) VALUES('%s', '%s')"%(user, pass)
btw you should connect like this :
conn = pymysql.connect(
host='127.0.0.1',
user='root',
passwd='root',
db='MySQL
)