So I have a python file that has a connection to a MariaDB server. The connection works, so that is not the problem. Select, Deletes and so on work, but when I tried the Alter statement to reset the auto-increment, the "cursor.execute" statement would freeze my program. This is my code:
def ResetAutoIncrement_MariaDB(table):
connect_MariaDB()
try:
statement = ("ALTER TABLE %s AUTO_INCREMENT = 1" % (table))
cursor.execute(statement)
except mariadb.Error as e:
print(f"Error: {e}")
conn.commit()
conn.close()
So when I execute the following function for example, my code would freeze when it reached the "cursor.execute(statement)" in the "ResetAutoIncrement_MariaDB(table)" function above.
def deleteWholeTable_MariaDB(table):
connect_MariaDB()
try:
statement = ("DELETE FROM %s" % (table))
cursor.execute(statement)
ResetAutoIncrement_MariaDB(table)
except mariadb.Error as e:
print(f"Error: {e}")
conn.commit()
conn.close()
The DELETE in this function works, but the other function doesn't. Any suggestions? Thanks!
def connect_MariaDB():
try:
global conn
conn = mariadb.connect(
user="user",
password=USERPASSWORD,
host="192.168.76.3",
port=3306,
database="Discord_Bots"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
global cursor
cursor = conn.cursor()
Related
I have an SQLite3 database that I want to add to with python, this is the code i have to add a row
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
def add_password(conn, data):
"""
Create an entry into the password database
"""
try:
sql = 'INSERT INTO passwords(added,username,password,website,email) VALUES(?,?,?,?,?)'
cur = conn.cursor()
cur.execute(sql, data)
print('done')
return cur.lastrowid
except Error as e:
print(e)
connection = create_connection('passwords.db')
data = (datetime.now(), 'SomeUsername', 'password123', 'stackoverflow.com', 'some#email.com')
add_password(connection, data)
When I run it prints done and ends, there are no errors. However, when I open the database to view the table, it has no entries.
If I open the database and run the same SQL code
INSERT INTO passwords(added,username,password,website,email)
VALUES('13-5-2020', 'SomeUsername', 'password123', 'stackoverflow.com', 'some#email.com')
it adds to the table. So it must be a problem with my python code. How do I get it to add?
Just make conn.commit() after executing query. It should work
I'm running Ubuntu 16.04 with MySQL. I've opened the MySQL server for remote connections, and my remote Python script can query my database, but all attempts to INSERT fail without any error log entry.
It also looks like my remote INSERTs are being seen, because my AUTO_INCREMENT ID increases without entries being made when I run the Python INSERT code.
Any insight is appreciated!
Simple table schema:
CREATE TABLE test (
ID int NOT NULL AUTO_INCREMENT,
x INT,
PRIMARY KEY (ID)
);
This works directly on the server:
INSERT INTO test (x) VALUES (10);
This is the Python query that's working:
try:
connection = db.Connection(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=DB)
cursor = connection.cursor()
print("Connected to Server")
cursor.execute("SELECT * FROM test")
result = cursor.fetchall()
for item in result:
print(item)
except Exception as e:
print('exception connecting to server db: ' + str(e))
finally:
print('closing connection...')
connection.close()
And the Python INSERT that's not working:
try:
connection = db.Connection(host=HOST, port=PORT, user=USER, passwd=PASSWORD, db=DB)
cursor = connection.cursor()
print("Connected to Server")
cursor.execute("INSERT INTO test (x) VALUES (10);")
except Exception as e:
print('exception connecting to server db: ' + str(e))
finally:
print('closing connection...')
connection.close()
Thanks
Add this line after the execute() call:
cursor.execute("INSERT INTO test (x) VALUES (10)")
connection.commit()
When making changes to the db, it is required that you commit your changes, no change(s) would take effect.
I am using this below code to update the records of my table but it doesn't work and it doesn't update my table
conn = mysql.connector.connect(host='localhost',
database='rps',
user='root',
password='')
cur = conn.cursor()
cur.execute("""UPDATE players SET score=%s WHERE chat_id =%s""", (int(self.p1.score), str(self.p1.chat__id)))
cur.execute("""UPDATE players SET score=%s WHERE chat_id =%s""", (int(self.p2.score), str(self.p2.chat__id)))
conn.commit()
cur.close()
conn.close()
It is completely true but i don't know how to solve this problem
Can you help me to solve it guys ?
Thanks
You can set try/catch on your query execution:
try:
cursor.execute(some_statement)
except MySQLdb.IntegrityError, e:
# handle a specific error condition
except MySQLdb.Error, e:
# handle a generic error condition
except MySQLdb.Warning, e:
# handle warnings, if the cursor you're using raises them
If you don't catch any exceptions, you should check your program logic.
I have an AWS Lambda function which is connected to a Jira webhook. Anytime an issue is created/changed/deleted, it sends a request to my API Gateway, which calls my function. I'm receiving the following traceback when I try to connect to Redshift inside the function:
Traceback (most recent call last):
File "/var/task/jira_webhook_proc.py", line 171, in lambda_handler
update_item(request, issue, issue_key)
File "/var/task/jira_webhook_proc.py", line 193, in update_item
delete_item(delete_key)
File "/var/task/jira_webhook_proc.py", line 277, in delete_item
port=REDSHIFT_PORT) as conn:
File "/var/task/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
OperationalError: could not translate host name "***" to address: Temporary failure in name resolution
I'm using a pre-compiled psycopg2 library that can be found here https://github.com/jkehler/awslambda-psycopg2. From googling it seems this might be a PostgreSQL error where I don't have a config file set right to listen to all ports. I'm not sure how I would change that however.
I use this code added below to connect redshift from lambda function. Using psycopg2
conn_string = "dbname='your_db_name' port='5439' user='redshift_user' password='^%+^+&7!+' host='xxxxxxx.yyyyyyy.eu-west-1.redshift.amazonaws.com'"
conn = psycopg.connect(conn_string)
cursor = conn.cursor()
cursor.execute("COPY data_table ........ ")
conn.commit()
cursor.close()
conn.close()
It might help someone as it worked perfectly in my case.
import psycopg2
import od_red_load_cred as CONSTANTS
def main():
# Amazon Redshift connect string
try:
conn_string = "dbname={} port={} user={} password={} host={}"\
.format(CONSTANTS.DBNAME, CONSTANTS.PORT, CONSTANTS.USER,
CONSTANTS.PASSWORD, CONSTANTS.HOST)
print("Connect string Successful!")
except:
print("Unable to create the connect string")
# query generate
try:
sql="""copy {}.{} from '{}'\
credentials 'aws_access_key_id={};aws_secret_access_key={}' \
DELIMITER ',' ACCEPTINVCHARS EMPTYASNULL ESCAPE COMPUPDATE OFF;commit;"""\
.format(CONSTANTS.SCHEMA, CONSTANTS.TABLE_NAME_BV, CONSTANTS.S3_PATH_BV,
CONSTANTS.ACCESS_KEY_ID, CONSTANTS.SECRET_ACCESS_KEY)
print("sql ==>", sql)
print("Query creation Successful!")
print(" ")
except:
print("Unable to create the query")
# get connection
try:
con = psycopg2.connect(conn_string);
print("con ==>", con)
print("Connection Successful!")
except Exception as e:
print("Unable to connect to Redshift")
print(e)
exit(-1)
# get cursor connection
try:
cur = con.cursor()
except Exception as e:
print("Unable to get the cursor from connection of Redshift")
print(e)
exit(-1)
# execute cursor connection
try:
cur.execute(sql)
print("Query executed successfully")
except Exception as e:
print("Failed to execute the query")
print(e)
exit(-1)
# close connection
try:
con.close()
print("Connection closed Successfully!")
except Exception as e:
print("Unable to close connection to Redshift")
print(e)
print(" ")
# Main method
if __name__ == '__main__':
print("start: __main__ ")
main()
print("end: __main__ ")
there’s something wrong in my python script: when I try to put some data in my database and print it, it looks like it’s working, but when I rerun the code, or if I check the phpmyadmin, there’s no data saved in the db. Does anyone have some idea on how to solve this problem?
import mysql.connector
from mysql.connector import errorcode
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host='localhost',
database='Temperature',
user='Temperature',
password='mypass')
if conn.is_connected():
print('Connected to MySQL database')
cur = conn.cursor()
query = "INSERT INTO Temp(temp, humi) " \
"VALUES(315, 55)"
try:
cur.execute(query)
except MySQLdb.ProgrammingError as e:
print(e)
query = "SELECT * FROM Temp"
try:
cur.execute(query)
for reading in cur.fetchall():
print (str(reading[0])+" "+str(reading[1]))
except MySQLdb.ProgrammingError as e:
print(e)
except Error as e:
print(e)
finally:
conn.close()
if __name__ == '__main__':
connect()
You will need to add conn.commit() before conn.close(). That should solve the problem.