python连接数据库的技术_Python操作MySQL数据库的三种方法
(1) 什么是MySQLdb?
MySQLdb 是用于 Python 连接 MySQL 数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。
$ tar zxvf MySQL-python-.tar.gz
$ cd MySQL-python-
$ python setup.py build
$ python setup.py install
(3) MySQLdb 的使用:
#!/usr/bin/env python
coding=utf-8
import MySQLdb
def connectdb():
print('连接到mysql服务器...')
打开数据库连接
# 用户名:p, 密码:12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
db = MySQLdb.connect("localhost","p","12345.","TESTDB")
print('连接上了!')
return db
def createtable(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果存在表Sutdent先删除
cursor.execute("DROP TABLE IF EXISTS Student")
sql = """CREATE TABLE Student (
ID CHAR(10) NOT NULL,
Name CHAR(8),
Grade INT )"""
# 创建Sutdent表
cursor.execute(sql)
def insertdb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = """INSERT INTO Student
VALUES ('001', 'CZQ', 70),
('002', 'LHQ', 80),
('003', 'MQ', 90),
('004', 'WH', 80),
('005', 'HP', 70),
('006', 'YF', 66),
('007', 'TEST', 100)"""
#sql = "INSERT INTO Student(ID, Name, Grade) \
# VALUES ('%s', '%s', '%d')" % \
# ('001', 'HP', 60)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
print '插入数据失败!'
db.rollback()
def querydb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
#sql = "SELECT * FROM Student \
# WHERE Grade > '%d'" % (80)
sql = "SELECT * FROM Student"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
ID = row[0]
Name = row[1]
Grade = row[2]
# 打印结果
print "ID: %s, Name: %s, Grade: %d" % \
(ID, Name, Grade)
except:
print "Error: unable to fecth data"
def deletedb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
SQL 删除语句
sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
print '删除数据失败!'
# 发生错误时回滚
db.rollback()
def updatedb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 更新语句
sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
print '更新数据失败!'
# 发生错误时回滚
db.rollback()
def closedb(db):
db.close()
def main():
db = connectdb() # 连接MySQL数据库
createtable(db) # 创建表
insertdb(db) # 插入数据
print '\n插入数据后:'
querydb(db)
deletedb(db) # 删除数据
print '\n删除数据后:'
querydb(db)
updatedb(db) # 更新数据
print '\n更新数据后:'
querydb(db)
closedb(db) # 关闭数据库
if name == 'main':
main()
#!/usr/bin/env python
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
cur=conn.cursor()
cur.execute('select user,password from user')
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
#!/usr/bin/env python
#* coding:utf-8 *
import MySQLdb
try:
conn = MySQLdb.Connect(host='192.168.8.40',user='root',passwd='root',db='mysql',port=3306)
cur = conn.cursor()
rs = cur.execute('select user,password,host from user')
rs = cur.execute('create database if not exists python')
conn.select_db('python')
cur.execute('create table test(id int,info varchar(30))')
value = [1,'hi jack']
cur.execute('insert into test values(%s,%s)',value)
values = []
for i in range(20):
values.append((i,'hi jack' + str(i)))
cur.executemany('insert into test values(%s,%s)',values)
cur.execute('update test set info="i am jack" where id=3')
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print 'mysql error msg: %d,%s' % (e.args[0],e.args[1])
import MySQLdb
try:
conn = MySQLdb.Connect(host='192.168.8.40',user='root',passwd='root',db='mysql',port=3306,charset='utf8')
cur = conn.cursor()
conn.select_db('python')
count = cur.execute('select * from test')
print 'there has %s rows record' % count
result = cur.fetchone()
print result
print 'id: %s info %s' % result
result2 = cur.fetchmany(3)
for record in result2:
print record
print '=='*10
cur.scroll(0,mode='absolute')
result3 = cur.fetchall()
for record in result3:
print record[0] ,'---',record[1]
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print 'mysql error msg: %d,%s' % (e.args[0],e.args[1])
查询后中文会显示乱码,但在数据库中却是正常的,发现用一个属性有可搞定:
在Python代码
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
改为:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。
然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚
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条.
PyMySQL 的使用
(1) 什么是 PyMySQL?
PyMySQL 是 Python 中用于连接 MySQL 服务器的一个库,它遵循 Python 数据库 API 规范 V2.0,并包含了 pure-Python MySQL 客户端库。
(2) 安装 PyMysql:
pip install PyMysql
(3) 使用 PyMySQL:
#!/usr/bin/env python
coding=utf-8
import pymysql
def connectdb():
print('连接到mysql服务器...')
打开数据库连接
# 用户名:p, 密码:12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
db = pymysql.connect("localhost","hp","Hp12345.","TESTDB")
print('连接上了!')
return db
def createtable(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果存在表Sutdent先删除
cursor.execute("DROP TABLE IF EXISTS Student")
sql = """CREATE TABLE Student (
ID CHAR(10) NOT NULL,
Name CHAR(8),
Grade INT )"""
# 创建Sutdent表
cursor.execute(sql)
def insertdb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = """INSERT INTO Student
VALUES ('001', 'CZQ', 70),
('002', 'LHQ', 80),
('003', 'MQ', 90),
('004', 'WH', 80),
('005', 'HP', 70),
('006', 'YF', 66),
('007', 'TEST', 100)"""
#sql = "INSERT INTO Student(ID, Name, Grade) \
# VALUES ('%s', '%s', '%d')" % \
# ('001', 'HP', 60)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
print '插入数据失败!'
db.rollback()
def querydb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
#sql = "SELECT * FROM Student \
# WHERE Grade > '%d'" % (80)
sql = "SELECT * FROM Student"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
ID = row[0]
Name = row[1]
Grade = row[2]
# 打印结果
print "ID: %s, Name: %s, Grade: %d" % \
(ID, Name, Grade)
except:
print "Error: unable to fecth data"
def deletedb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 删除语句
sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
print '删除数据失败!'
# 发生错误时回滚
db.rollback()
def updatedb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 更新语句
sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
print '更新数据失败!'
# 发生错误时回滚
db.rollback()
def closedb(db):
db.close()
def main():
db = connectdb() # 连接MySQL数据库
createtable(db) # 创建表
insertdb(db) # 插入数据
print '\n插入数据后:'
querydb(db)
deletedb(db) # 删除数据
print '\n删除数据后:'
querydb(db)
updatedb(db) # 更新数据
print '\n更新数据后:'
querydb(db)
closedb(db) # 关闭数据库
if name == 'main':
main()
import pymysql
打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("localhost", "root", "root", "test")
使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
关闭数据库连接
db.close()
import pymysql
打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("localhost", "root", "root", "test")
使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
SQL 插入语句
sql = """INSERT INTO user(name)
VALUES ('Mac')"""
try:
执行sql语句
cursor.execute(sql)
提交到数据库执行
db.commit()
except:
如果发生错误则回滚
db.rollback()
关闭数据库连接
db.close()
import pymysql
打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("localhost", "root", "root", "test")
使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
SQL 查询语句
sql = "SELECT * FROM user"
try:
执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
# 打印结果
print("id=%s,name=%s" % \
(id, name))
except:
print("Error: unable to fecth data")
关闭数据库连接
db.close()
import pymysql
打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("localhost", "root", "root", "test")
使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
SQL 更新语句
sql = "UPDATE user SET name = 'Bob' WHERE id = 1"
try:
执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
发生错误时回滚
db.rollback()
关闭数据库连接
db.close()
import pymysql
打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("localhost", "root", "root", "test")
使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
SQL 删除语句
sql = "DELETE FROM user WHERE id = 1"
try:
执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
发生错误时回滚
db.rollback()
关闭数据库连接
db.close()
mysql.connector 的使用
(1) 什么是 mysql.connector?
由于 MySQL 服务器以独立的进程运行,并通过网络对外服务,所以,需要支持 Python 的 MySQL 驱动来连接到 MySQL 服务器。
目前,有两个 MySQL 驱动:
mysql-connector-python:是 MySQL 官方的纯 Python 驱动;
MySQL-python :是封装了 MySQL C驱动的 Python 驱动。
(2) 安装 mysql.connector:
pip install mysql-connector-python
pip install MySQL-python
(3) 使用 mysql.connector:
#!/usr/bin/env python
coding=utf-8
import mysql.connector
def connectdb():
print('连接到mysql服务器...')
打开数据库连接
# 用户名:p, 密码:12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB,并在TESTDB数据库中创建好表Student
db = mysql.connector.connect(user="p", passwd="12345.", database="TESTDB", use_unicode=True)
print('连接上了!')
return db
def createtable(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# 如果存在表Sutdent先删除
cursor.execute("DROP TABLE IF EXISTS Student")
sql = """CREATE TABLE Student (
ID CHAR(10) NOT NULL,
Name CHAR(8),
Grade INT )"""
# 创建Sutdent表
cursor.execute(sql)
def insertdb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 插入语句
sql = """INSERT INTO Student
VALUES ('001', 'CZQ', 70),
('002', 'LHQ', 80),
('003', 'MQ', 90),
('004', 'WH', 80),
('005', 'HP', 70),
('006', 'YF', 66),
('007', 'TEST', 100)"""
#sql = "INSERT INTO Student(ID, Name, Grade) \
# VALUES ('%s', '%s', '%d')" % \
# ('001', 'HP', 60)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
print '插入数据失败!'
db.rollback()
def querydb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
#sql = "SELECT * FROM Student \
# WHERE Grade > '%d'" % (80)
sql = "SELECT * FROM Student"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
ID = row[0]
Name = row[1]
Grade = row[2]
# 打印结果
print "ID: %s, Name: %s, Grade: %d" % \
(ID, Name, Grade)
except:
print "Error: unable to fecth data"
def deletedb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 删除语句
sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)
try:
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
except:
print '删除数据失败!'
# 发生错误时回滚
db.rollback()
def updatedb(db):
使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 更新语句
sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')
try:
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
print '更新数据失败!'
# 发生错误时回滚
db.rollback()
def closedb(db):
db.close()
def main():
db = connectdb() # 连接MySQL数据库
createtable(db) # 创建表
insertdb(db) # 插入数据
print '\n插入数据后:'
querydb(db)
deletedb(db) # 删除数据
print '\n删除数据后:'
querydb(db)
updatedb(db) # 更新数据
print '\n更新数据后:'
querydb(db)
closedb(db) # 关闭数据库
if name == 'main':
main()
#!/usr/bin/python
#coding=utf-8
import mysql.connector
from mysql.connector import errorcode
class mysqlconnectordemo(object):
def init(self):
pass
def connect(self,conf):
try:
conn = mysql.connector.connect(**conf)
print("conn success!")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
conn.close()
def query(self,conf,sql):
try:
conn = mysql.connector.connect(**conf)
print("conn success!")
cursor = conn.cursor()
try:
cursor.execute(sql)
values = cursor.fetchall()#返回是一个由元组构成的list,每一个元组是一行值
print type(values)
for i in values:
print i
except mysql.connector.Error as err:
print('query datas error!{}'.format(err))
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
conn.close()
def insert(self,conf,sql):
try:
conn = mysql.connector.connect(**conf)
print("conn success!")
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
cursor.close()
except mysql.connector.Error as err:
print('insert datas error!{}'.format(err))
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
conn.close()
#!/usr/bin/python
#coding=utf-8
import MySQLdb
class mysqldbdemo(object):
def init(self):
pass
def connect(self):
conn = MySQLdb.connect("host_ip","user","password","database")
conn.close()
def query(self,sql):
conn = MySQLdb.connect("host_ip","user","password","database")
cursor = conn.cursor()
try:
cursor.execute(sql)
values = cursor.fetchall()#返回是一个由元组构成的tuple,每一个元组是一行值
print type(values)
for i in values:
print i
except:
print "Error: unable to fecth data"
conn.close()
def insert(self,sql):
conn = MySQLdb.connect("host_ip","user","password","database")
cursor = conn.cursor()
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
conn.close()
python连接数据库的技术_Python操作MySQL数据库的三种方法相关推荐
- Python操作MySQL数据库的三种方法
1. MySQLdb 的使用 (1) 什么是MySQLdb? MySQLdb 是用于 Python 连接 MySQL 数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 M ...
- mysql 安装在路由器_MySQL如何安装?安装MySQL数据库的三种方法
MySQL如何安装?安装MySQL数据库的三种方法 目录 安装MySQL的方式常见的有三种: rpm包形式 通用二进制形式 源码编译 1,rpm包形式 (1) 操作系统发行商提供的 (2) MySQL ...
- python怎么循环终止_Python 循环终止语句的三种方法小结
Python 循环终止语句的三种方法小结 在Python循环终止语句有三种: 1.break break用于退出本层循环 示例如下: while True: print "123" ...
- python连接数据库设置编码_python操作mysql中文显示乱码的解决方法
本文实例展示了一个脚本python用来转化表配置数据xml并生成相应的解析代码. 但是在中文编码上出现了乱码,现将解决方法分享出来供大家参考. 具体方法如下: 1. Python文件设置编码 utf- ...
- Python操纵Mysql数据库的三种方法,实现增删改查
目录 这里使用的数据库是关系型数据库Mysql 一.首先,需要安装两个库 二.3种实现增删改查的方法 1. 使用原生语句进行增删改查 2. 使用表结构进行增删改查 3. 使用集成ORM类操纵数据库, ...
- 用python批量下载网络图片_python批量下载图片的三种方法
一是用微软提供的扩展库win32com来操作IE: win32com可以获得类似js里面的document对象,但貌似是只读的(文档都没找到). 二是用selenium的webdriver: sele ...
- mysql+数据库连接标识_新人必看!连接到MySQL数据库的两种方法
原标题:新人必看!连接到MySQL数据库的两种方法 使用mysql二进制方式连接 您可以使用MySQL二进制方式进入到mysql命令提示符下来连接MySQL数据库. 实例 以下是从命令行中连接mysq ...
- php连接mysql_PHP连接MySQL数据库的三种方式
本篇文章给大家介绍一下PHP连接MySQL数据库的三种方式(mysql.mysqli.pdo),结合实例形式分析了PHP基于mysql.mysqli.pdo三种方式连接MySQL数据库的相关操作技巧与 ...
- php连接虚拟机中mysql数据库吗,PHP连接MySQL数据库的三种方式
本篇文章给大家介绍一下PHP连接MysqL数据库的三种方式(MysqL.MysqLi.pdo),结合实例形式分析了PHP基于MysqL.MysqLi.pdo三种方式连接MysqL数据库的相关操作技巧与 ...
最新文章
- discuz云平台报调用远程接口失败的问题分析和解决
- 随笔(2018.9.2.)
- Leetcode 剑指 Offer 04. 二维数组中的查找 (每日一题 20210727)
- 重磅下载 | 核心系统100%上云,揭秘双11背后的云原生实践
- 网络虚拟化有几种实现方式_机械零件表面实现镜面的几种加工方式
- 黑苹果(1)为什么是黑苹果PPT?
- 2021-03-05 网站资源数据搜集
- 图文详解YUV420数据格式
- 如何制作简单的html静态网页
- 桌面运维转网络要做什么准备,高级网工学习路线分享
- matlab 一个简单的FIR低通滤波器设计例子
- 今天Delphi盒子打不开了
- vue项目初始化出现tar ENOENT: no such file or directory错误的解决办法。
- 【Unity】Unity 2D游戏开发(三)2D游戏常用功能及插件
- 简单CSS,实现“首字下沉”效果!
- QQ群反向昵称、恶搞昵称的原理[附]
- java将图片均匀分成9份,怎样把一张图片快速切成平均等分/切图? - 杂谈
- HTML小游戏6 —— 《高达战争》横版射击游戏(附完整源码)
- DirectSound播放音频应用程序开发快速入门
- 通证经济大局观(十六):理性人和机会成本
热门文章
- [AaronYang]那天有个小孩跟我说Js-NodeJS[AY0]-EJS
- 用C++写的 Levenshtein 算法实现
- 干货 | 产品经理要了解的技术类知识
- App上线需要自查的list——主要针对产品、部分运营加测试
- 多图 | 600岁“网红”的10亿+营收变现(结尾有彩蛋)
- 线下活动 | 揭秘大数据背后的京东虚拟平台(免费报名中)
- 【干货】理发师都知道的产品经理最容易犯的几个错误
- C#实现树型结构TreeView节点拖拽的简单功能,附全部源码,供有需要的参考
- AliOS Things 硬件抽象层(HAL)对接系列2 — SPI driver porting
- [Spark][Python]sortByKey 例子