我熟悉python,也熟悉mysql和SQL。我也很清楚con,cur和commit,但是我的問題在於,我試圖在python中創建一個小程序(不需要gui)來將數據插入到mysql數據庫中,並將其放到我的控制檯或文件中。我很困惑從哪裏開始,我試圖尋找谷歌,但我無法找到任何關於我的問題toturials,任何幫助?一個鏈接或從哪裏開始。另外:通過python程序插入數據庫(mysql)
我知道python程序可以寫在IDE或文本文件中,但它如何連接到mysql數據庫?如果我錯了,請糾正我。
我熟悉python,也熟悉mysql和SQL。我也很清楚con,cur和commit,但是我的問題在於,我試圖在python中創建一個小程序(不需要gui)來將數據插入到mysql數據庫中,並將其放到我的控制檯或文件中。我很困惑從哪裏開始,我試圖尋找谷歌,但我無法找到任何關於我的問題toturials,任何幫助?一個鏈接或從哪裏開始。另外:通過python程序插入數據庫(mysql)
我知道python程序可以寫在IDE或文本文件中,但它如何連接到mysql數據庫?如果我錯了,請糾正我。
SQLAlchemy的好:https://www.sqlalchemy.org/
否則,使用康恩/ CUR像你描述很簡單:https://www.tutorialspoint.com/python/python_database_access.htm
圍棋雖然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"
謝謝你們,我讓它工作!我使用pymysql而不是mysqldb,因爲它更簡單,問題更少。 –
請參見下面的代碼
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()
嘗試用文字*的Python程序搜索到從數據庫中獲得*搜索*谷歌數據*通過本身是一個很好的技能 – Rahul
我做得很激動,我沒有得到任何東西,這裏重要的是如何寫入數據庫,這是我不明白,我知道我們會在內部使用SQL程序,但我不明白如何連接到MySQL數據庫 –
使用mysqldb python庫並閱讀這裏的文檔:http://mysql-python.sourceforge.net/MySQLdb.html – lordingtar