安装Python-MySQL
Linux下
直接在terminal中输入
pip install MySQL-python
若没有安装pip工具,则先在terminal中输入
sudo apt install pip-python
pip install --upgrade pip
安装和更新pip工具
Windows下
Windows下安装MySQL-python需要先安装C++9.0环境,进入http://aka.ms/vcpython27下载并安装
然后打开命令行输入:
pip install MySQL-python
会自动完成安装
安装完成后,进行Python环境,输入
import MySQLdb
不报错则说明安装成功
Python操作数据库
import MySQLdb
conn= MySQLdb.connect(
host='localhost', # host主机名
port = 3306, # port端口号
user='root', # 登录的用户名
passwd='123456', # 登录的密码
db ='test', # 连接的数据库
)
cur = conn.cursor() # 获得当前游标
cur.execute('sql_string') # 执行sql语句
cur.close() # 关闭游标
conn.commit() # 提交事务,若执行插入语句,则必须commit之后才会对数据库进行写入
conn.close() # 关闭连接
新建表
cur.execute('create table testtable(id int not null auto_increment, name varchar(20), primary key (id))')
新建了一张表testtable,包含id和name两列,其中id为主键
插入数据
cur.execute('insert into testtable (name) values ("test")') # 记得'和"要混合用,不然会将字符串切断
conn.commit()
上面的语句执行完后将会在testtable中插入一条记录,id自动增长,name的值为test
还可以以带入参数的方式执行
sql = 'insert into testtable (name) values (%s)'
cur.execute(sql, ("test"))
conn.commit()
若想要带入多个参数,可以使用executemany()
sql = 'insert into testtable (name) values (%s)'
cur.executemany(sql, [("test"), ("test2")])
conn.commit()
可以看出executemany是用列表传入参数的
查询数据
print cur.execute('select * from testtable')
# 1
输出1,只是输出得到的结果的数量而
如果想要得到结果,可以使用fetchone()和fetchmany()函数
cur.execute('select * from testtable')
cur.fetchone()
# (1L, 'test')
cur.fetchone()
# (2L, 'test')
从上述语句输出可以看出,fetchone()有点类似迭代器的next()函数,使用cur的scroll(0,'absolute')
方法可以返回到第一条数据
使用cur.fetchmany()函数可以返回一个包含所有结果的元组
results = cur.execute('select * from testtable')
result_tuple = cur.fetchmany(results)
print result_tuple
# ((1L, 'test'),(2L, 'test'))