使用Python连接MySQL
安装MySQL
yum install -y mysql-server mysql-devel
安装MySQL-python驱动
pip install MySQL-python
测试
➜ 2-3_Django ipython
Python 2.7.11 (default, Mar 7 2017, 08:25:27)
Type "copyright", "credits" or "license" for more information.
IPython 5.3.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import MySQLdb
In [2]:
操作示例
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
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()
相关错误解决方法
编译时报如下错误
‘_mysql_connectionobject’ has no member named ‘open’