I. 安装模块python3-mysqldb
首先更新到最新的库列表:
$ sudo apt-get update
打开全新的终端,安装python3对mysqldb的支持:
$ sudo apt-get install python3-mysqldb
II. 创建python脚本,连接数据库
#!/usr/bin/python3
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='test', passwd='test', db='pyytest', port=3306)
说明:
host: 即可以访问的连接来源;
user和passwd需要和前面创建的数据库访问用户对应。
db='pyytest'是对应的数据库名。
port=3306:是固定值,本人也不明白。
III. 插入数据
#!/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. 验证结果
为了验证结果,在全新的终端中输入下面的命令以用户test的身份打开数据库pyytest:
$ mysql pyytest -u test -p
在数据库中,使用如下命令查询表单中的成员:
SELECT * FROM employees;