How can the id automaticly inserted in python mysql? - python

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) """

Related

SQL Database file not showing up in folder?

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.

Python MySQL Connector Timeout

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()

Python with psycopg2 and pgAdmin4 how can i retrieve bytea data

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.

Call a MySQL stored procedure from Python unattended

I need to call a MySQL stored procedure from Python, and I don't need to wait for the procedure to finish.
How can this be done?
code below work for me
import mysql.connector
def insertComment(ecID, eID, eComment):
try:
contraseƱa = input("Please, enter your database password: ")
connection = mysql.connector.connect(host='localhost',
database='mantenimiento',
user='hernan',
password=contraseƱa,
port=3309)
if connection.is_connected():
cursor = connection.cursor(prepared=True)
procedure = "call mantenimiento.spSaveComment(%s, %s, %s)"
datos = (ecID, eID, eComment)
cursor.execute(procedure, datos)
# datos = [(ecID, eID, eComment)] # Tuple for executemany
# cursor.executemany(procedure, datos)
connection.commit()
print(cursor.rowcount, "Comment inserted sucessfully")
except mysql.connector.Error as error:
connection.rollback()
print("Failed to insert value into database {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("Server connection was closed")
insertComment(15, 25, 'Test MariaDB or MySQL SP from python')
One possible solution is by using celery: "Celery is an asynchronous task queue/job queue based on distributed message passing.". You can create a task where you call your MySQL store procedure.

How to import Python data to postgresql

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.

Categories