python连接数据库
Python需要有一个模块,来实现与MySQL数据库的连接:PyMySQL
-
Python3 MySQL 数据库连接 - PyMySQL 驱动
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。 -
安装(配置python环境变量)
(1)进入cmd -->pip install pymysql
安装完毕可通过pycharm查看。
注意:
执行pip命令前需要检查当前系统python版本与pycharm下使用版本是否一致,否则无法查看到pymysql
(2)或pyCharm下安装
-
在.py文件中导入这个模块:
import pymysql
cursor
conn表示连接数据库,对数据的操作需要通过cursor来实现。
cursor用来执行命令的方法:
callproc(self, procname, args):
用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):
执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):
执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):
移动到下一个结果集
cursor用来接收返回值的方法:
fetchall(self):
接收全部的返回结果行.
fetchmany(self,size=None):
接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):
返回一条结果行.
scroll(self, value, mode='relative'):
移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.
代码
##!/usr/bin/python
#coding=utf-8
import pymysql
# 创建表
def createTable():
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456",
db="test", port=3306)
cur = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在则删除
cur.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用预处理语句创建表
sql = """create table employee(
id int,
name varchar(20),
dept varchar(50)
)
"""
# 获取游标,并执行sql语句
cur.execute(sql)
# 关闭数据库连接
db.close()
print "新建表成功"
createTable()
# 插入数据
def insertTable():
db = pymysql.connect(host="localhost",user="root",password="123456",
db="test",port=3306)
cur = db.cursor()
sql = "insert into employee (id,name,dept) values (1,'frank','manager')"
try:
cur.execute(sql)
db.commit()
except:
db.rollback()
db.close()
print "插入数据成功!"
insertTable()
# 查询表
def selectTable():
db = pymysql.connect(host="localhost",user="root",password="123456",
db="test",port=3306)
cur = db.cursor()
sql = "select * from employee"
try :
cur.execute(sql)
results = cur.fetchall()
print results
for i in results:
id=i[0]
name=i[1]
dept=i[2]
print "id=%d,name=%s,dept=%s"%(id,name,dept)
except Exception as e:
raise e
finally:
db.close()
selectTable()
# 更新表
def updateTable():
db = pymysql.connect(host="localhost",user="root",password="123456",
db="test",port=3306)
cur = db.cursor()
sql = "update employee set name='WW' where id=1 "
try:
cur.execute(sql)
db.commit()
except:
db.rollback()
db.close()
print "数据更新成功!"
updateTable()
#删除表中信息
def deleteTable():
db = pymysql.connect(host="localhost",user="root",password="123456",
db="test",port=3306)
cur = db.cursor()
sql = "delete from employee where id=2"
try:
cur.execute(sql)
db.commit()
except:
db.rollback()
db.close()
print "删除数据成功!"
deleteTable()
运行结果
新建表
插入数据
查询数据
更新数据
删除数据