Python 使用MySQL

在导入MySQLdb之前,需要安装MySQLdb模块。使用pip安装,命令如下: pip install MySQL-python

安装成功后,导入MySQLdb模块

import MySQLdb

连接数据库

con = MySQLdb.connect(host='127.0.0.1', user = 'root', passwd = '', db = 'go')

上面通过connect方法返回的con对象,即是数据库连接对象,它提供了以下方法
cursor()方法用来创建一个游标对象:
cur = con.cursor()

游标对象有以下方法支持数据库的操作 
execute()用来执行SQL语句
executemany()用来执行多条sql语句
close()用来关闭游标
fetchone()用来从结果中取一条记录,并将游标指向下一条记录
fetchmany()用来从结果中取多条记录
fetchall()用来从结果中取出所有记录
scroll()用于游标滚动

#coding:utf-8
import MySQLdb

if __name__ == '__main__':

con = MySQLdb.connect(host='127.0.0.1', user = 'root', passwd = '', db = 'go')

cur = con.cursor()

cur.execute('select * from user')

#取出所有的数据
all = cur.fetchall()
print all

#取出一条数据
cur.execute('select * from user')
one = cur.fetchone()
print one

#取出多条结果
cur.execute('select * from user')
many = cur.fetchmany()

print many
#执行插入一条语句
cur.execute('insert into user(user_name,name)values("adssd","dksdksk")')
#插入多条数据
cur.executemany('insert into user(user_name,name)values(%s,%s)', [('22222', '3333'), ('33333', '4444')])
#必须执行commit()
con.commit()
con.close()



 

posted on 2018-01-31 11:32  paulversion  阅读(150)  评论(0编辑  收藏  举报