I. 安裝模塊python3-mysqldb
首先更新到最新的庫(kù)列表:
$ sudo apt-get update
打開(kāi)全新的終端,安裝python3對(duì)mysqldb的支持:
$ sudo apt-get install python3-mysqldb

II. 創(chuàng)建python腳本,連接數(shù)據(jù)庫(kù)
#!/usr/bin/python3
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='test', passwd='test', db='pyytest', port=3306)
說(shuō)明:
host: 即可以訪問(wèn)的連接來(lái)源;
user和passwd需要和前面創(chuàng)建的數(shù)據(jù)庫(kù)訪問(wèn)用戶對(duì)應(yīng)。
db='pyytest'是對(duì)應(yīng)的數(shù)據(jù)庫(kù)名。
port=3306:是固定值,本人也不明白。
III. 插入數(shù)據(jù)
#!/usr/bin/python3
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='test', passwd='test', db='pyytest', port=3306)
cursor = conn.cursor()
newemployee = ('INSERT INTO employees '
????'(empid, lastname, firstname, salary) '
????'VALUES (%s, %s, %s, %s)')
employee1 = ('1', 'Tony', 'Barbare', '5432.1')
employee2 = ('2', 'Sara', 'Rich', '9876.5')
employee3 = ('3', 'H', 'Yuan', '3562.45')
employee4 = ('4', 'J', 'Yang', '5689.78')
try:
????cursor.execute(newemployee, employee1)
????cursor.execute(newemployee, employee2)
????cursor.execute(newemployee, employee3)?
? ? cursor.execute(newemployee, employee4)
????conn.commit()
except:
????print('Sorry, there was a problem adding the data')
else:
????print('Data values added!')
cursor.close()
conn.close()
將上面的代碼保存為script2201_0.py,在全新的終端中輸入:
$ python3? script2201_0.py

IV. 驗(yàn)證結(jié)果
為了驗(yàn)證結(jié)果,在全新的終端中輸入下面的命令以用戶test的身份打開(kāi)數(shù)據(jù)庫(kù)pyytest:
$ mysql pyytest -u test -p
在數(shù)據(jù)庫(kù)中,使用如下命令查詢表單中的成員:
SELECT * FROM employees;
