我熟悉python,也熟悉mysql和SQL。我也很清楚con,cur和commit,但我的问题是我试图在python中创建一个小程序(不需要gui)将数据插入到mysql数据库中,并将它带到我的控制台或文件中。我很困惑从哪里开始,我试图寻找谷歌,但我找不到关于我的问题,任何帮助?一个链接或从哪里开始。也:
我知道python程序可以用IDE或文本文件编写,但是它如何连接到mysql数据库?如果我错了请纠正我。
答案 0 :(得分:0)
SQLAlchemy很好:https://www.sqlalchemy.org/
否则,如您所述使用conn / cur很简单:https://www.tutorialspoint.com/python/python_database_access.htm
答案 1 :(得分:0)
通过documentation来熟悉python,mysql以及如何一起使用它们。
虽然,最小代码看起来像这样:
import MySQLdb
query = "insert into DB_NAME values (1,2)"
try :
conn = MySQLdb.connect(host="",
user="",
passwd="",
db="")
cursor = conn.cursor()
cursor.execute(query)
conn.commit()
cursor.close()
conn.close()
except (MySQLdb.Error, Exception) as error :
print error
print "Insert data unsuccessful"
答案 2 :(得分:0)
请参阅以下代码
import mysql.connector
from mysql.connector import MySQLConnection, Error
class SQL_Connect:
def __init__(self):
#-------------------------------------------------------
# Database Connection Param's
self.host_Address = 'Host Here'
self.database_Name = 'Database Name'
self.userName = 'User Name'
self.db_Password = 'Password'
#-------------------------------------------------------
def insert_IntoDB(self, Manufacturer, partNum, formFactor, socket, chipSet, memSlots, memType, maxMem, raidSup, onboardVid, crosFire_Sup, sli_Sup, sata6GBS, sataExpress, onboard_Ether):
test_Query = 'INSERT INTO motherboards (Manufacturer, modelNum, formFactor, socket, chipset, memSlots, memType, maxMem, raidSup, onboardVid, crosfireSup, sliSup, sata6GBS, sataExpress, onboardEther) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
args = (Manufacturer, partNum, formFactor, socket, chipSet, memSlots, memType, maxMem, raidSup, onboardVid, crosFire_Sup, sli_Sup, sata6GBS, sataExpress, onboard_Ether)
try:
conn = mysql.connector.connect(host = self.host_Address, database = self.database_Name, user = self.userName, password = self.db_Password)
if conn.is_connected():
print 'MySQL Database Connection Established'
cursor = conn.cursor()
cursor.execute(test_Query, args)
conn.commit()
print 'Data Inserted!!!'
except Error as e:
print ('ERROR: ',e)
finally:
cursor.close()
conn.close()