python下使用MySQLdb操作MYSQL数据库
来源:互联网 发布:公众号 大数据 编辑:程序博客网 时间:2024/04/30 13:07
1、安装mysqldb(MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。)
Ubuntu:sudo apt-get install python-mysqldb
2、各种操作直接上实例
#!/usr/bin/python# -*- coding: UTF-8 -*-#首先引入MYSQLdb库import MySQLdb# 打开数据库连接 参数:IP、用户名、密码、数据库名字db = MySQLdb.connect("localhost","root","root","bank" )# 使用cursor()方法获取操作游标 cursor = db.cursor()# 使用execute方法执行SQL语句cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取一条数据库。data = cursor.fetchone()print "Database version : %s " % datasqlcmd = 'SELECT * from teller'cursor.execute(sqlcmd)data = cursor.fetchone()#获取第一行数据print 'data:', datadata = cursor.fetchone()#获取第二行数据print 'data[0]:', data[0]#获取第一个字段print 'data[1]:', data[1]#获取第二个字段cursor.execute('DROP TABLE if exists table1')#sql命令过长需要换行时,使用三引号sqlcmd = '''CREATE TABLE table1( firstname char(20) not null,lastname char(20),age int)'''cursor.execute(sqlcmd)sqlcmd= 'show tables'cursor.execute(sqlcmd)data=cursor.fetchall()print 'data:',datasqlcmd='''insert into teller values('jack', 'jack')'''try:cursor.execute(sqlcmd)db.commit()#提交到数据库执行except Exception, e:db.rollback()#发生错误时回滚else:print 'execute else'#没有错误会执行finally:print 'execute finally'#没有错误会执行try:sqlcmd = 'SELECT * from teller'cursor.execute(sqlcmd)data = cursor.fetchall()#获取结果for row in data:name=row[0]pwd=row[1]print 'name:', name, ',pwd:', pwdexcept Exception, e:print 'Error: unable to fecth data'#命令中间带引号时整个语句用三引号括起来,否认会错误sqlcmd='''update teller set teller_pass='hack' where teller_name='jack' and 1=1'''try:cursor.execute(sqlcmd)db.commit()#提交到数据库执行except Exception, e:db.rollback()#发生错误时回滚sqlcmd='''delete from teller where teller_name='jack' and 1=1'''try:cursor.execute(sqlcmd)db.commit()#提交到数据库执行except Exception, e:db.rollback()#发生错误时回滚# 关闭数据库连接db.close()
运行结果:
zjy@ubuntu:~$ python contDb.py
Database version : 5.7.19-0ubuntu0.16.04.1
data: ('root', 'root')
data[0]: zjy
data[1]: zjy
data: (('table1',), ('teller',))
execute else
execute finally
name: root ,pwd: root
name: zjy ,pwd: zjy
name: jack ,pwd: jack
zjy@ubuntu:~$
Database version : 5.7.19-0ubuntu0.16.04.1
data: ('root', 'root')
data[0]: zjy
data[1]: zjy
data: (('table1',), ('teller',))
execute else
execute finally
name: root ,pwd: root
name: zjy ,pwd: zjy
name: jack ,pwd: jack
zjy@ubuntu:~$
3、和数据库建立连接
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")
提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.
比较常用的参数包括
host:数据库主机名.默认是用本地主机.
user:数据库登陆名.默认是当前用户.
passwd:数据库登陆的秘密.默认为空.
db:要使用的数据库名.没有默认值.
port:MySQL服务使用的TCP端口.默认是3306.
charset:数据库编码.
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")
提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.
比较常用的参数包括
host:数据库主机名.默认是用本地主机.
user:数据库登陆名.默认是当前用户.
passwd:数据库登陆的秘密.默认为空.
db:要使用的数据库名.没有默认值.
port:MySQL服务使用的TCP端口.默认是3306.
charset:数据库编码.
4、.执行sql语句和接收返回值
cursor=conn.cursor()
n=cursor.execute(sql,param)
首先,我们用使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.这些方法包括两大类:1.执行命令,2.接收返回值
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条.
cursor=conn.cursor()
n=cursor.execute(sql,param)
首先,我们用使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.这些方法包括两大类:1.执行命令,2.接收返回值
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条.
5、关闭数据库连接
需要分别的关闭指针对象和连接对象.他们有名字相同的方法
cursor.close()
conn.close()
需要分别的关闭指针对象和连接对象.他们有名字相同的方法
cursor.close()
conn.close()
6、防止乱码
需要注意的点:
1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
2 MySQL数据库charset=utf-8
3 Python连接MySQL是加上参数 charset=utf8
4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)
#encoding=utf-8
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')
db=MySQLdb.connect(user='root',charset='utf8')
注:MySQL的配置文件设置也必须配置成utf8
设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf):
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8
需要注意的点:
1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
2 MySQL数据库charset=utf-8
3 Python连接MySQL是加上参数 charset=utf8
4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)
#encoding=utf-8
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')
db=MySQLdb.connect(user='root',charset='utf8')
注:MySQL的配置文件设置也必须配置成utf8
设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf):
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8
MySQLdb用户指南: http://mysql-python.sourceforge.net/MySQLdb.html
MySQLdb文档: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html
MySQLdb文档: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html
阅读全文
0 0
- python下使用MySQLdb操作MYSQL数据库
- python操作MySQL数据库(MySQLdb
- MySQLdb:Python 操作 MySQL 数据库
- python使用MySQLdb操作数据库
- Python使用MySQLdb操作MySQL
- python操作MySQL数据库增删改查使用MySQLdb
- Python自动化(七)使用MySQLdb操作MySQL数据库
- python 通过mysqldb 操作mysql数据库
- 【MySQLdb模块】Python操作MySQL数据库
- MySQLdb的使用 Python操作Mysql
- python使用mysqldb连接mysql数据库
- Python MYSQLdb操作数据库
- python下用mysqldb连接使用数据库
- python连接MYSql数据库python连接MYSql数据库 使用 MySQLdb
- Windows下安装MySQLdb, Python操作MySQL数据库的增删改查
- 【Python学习笔记】-利用MySQLdb操作mysql数据库
- MySQLdb和Python数据库操作
- python数据库操作 - PyMySQL,MySQLdb
- 古文觀止卷九_愚溪詩序_柳宗元
- HDU5618-Jam's problem again(cdq分治)
- (2)php框架开发---控制器开发
- 3. Longest Substring Without Repeating Characters
- 通过外部配置文件更改Javaweb项目的项目名,不通过eclipse编辑
- python下使用MySQLdb操作MYSQL数据库
- 顺丰科技2017年秋招笔试题“木木的密码”
- vs2017的使用
- 并发(十六):不要使用Thread.join()——并行变串行
- sass
- Memcache 持久化消息队列MemcacheQ
- 文章标题 中山大学
- python自然语言处理学习笔记3——词频统计
- 2、从HelloWorld开始C#开发