Ubuntu16.04 Python操作MySQL数据库
第一步 安装MySQL数据库
安装过程可以参考本人另一篇博客:
Ubuntu16.04安装MySQL数据库和可视化工具MySQL Workbench
第二步 安装MySQL-python驱动
下载驱动:
驱动下载地址安装驱动:
选择MySQL-python 1.2.5压缩包下载后,进入下载目录下:
解压: unzip MySQL-python-1.2.5.zip
进入解压文件夹: cd MySQL-python-1.2.5
安装: pip setup.py install
第三步 测试安装成功
在python命令行中导入MySQL模块没有报错则安装成功。
import MySQLdb
终端下进入MySQL数据库命令:
有密码:
$ mysql -u root -p
无密码:
$ mysql -u root
MySQL 基本操作Python代码
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='******',
db ='test',
)
cur = conn.cursor()
#创建数据表
cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一条数据
cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查询条件的数据
cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#删除查询条件的数据
cur.execute("delete from student where age='9'")
cur.close()
conn.commit()
conn.close()