对于uni的一个项目,我需要在MySql数据库中插入不同类型的变量。到目前为止,连接和插入数据运行良好。但我不知道如何处理潜在的错误。我需要抓住和处理哪些潜在的错误和例外?在
在我的代码中,我使用了一个main方法来测试程序。在最终版本中,只将连接和SQL查询复制到主脚本中。我可以使用MySQL或mysql.connector. 另外:我还需要将查询放入try块吗?以下是我目前为止的代码:
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()
请注意,我在python编程方面的经验很少
目前没有回答
相关问题 更多 >
编程相关推荐