Home Backend Development Python Tutorial python下MySQLdb用法实例分析

python下MySQLdb用法实例分析

Jun 10, 2016 pm 03:10 PM
python

本文实例讲述了python下MySQLdb用法。分享给大家供大家参考。具体分析如下:

下载安装MySQLdb

① linux版本

http://sourceforge.net/projects/mysql-python/ 下载,在安装是要先安装setuptools,然后在下载文件目录下,修改mysite.cfg,指定本地mysql的mysql-config文件的路径

② windows版本

网上搜索到一个http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

安装后import MySQLdb会出现 DeprecationWarning: the sets module is deprecated 这样一个警告,baidu一下

原因是2.6不知sets这个模块,不过已经添加了set内置函数。找到MySQLdb文件夹的中__init__.py,注释掉from sets import ImmutableSet   class DBAPISet(ImmutableSet):添加class DBAPISet(frozenset):;找到converters.py注释掉from sets import BaseSet, Set。然后修改第45行和129行中的Set为set。

搞定。

下面开始操作的demo:

Python代码

# -*- coding: utf-8 -*-   
#mysqldb  
import time, MySQLdb  
#连接  
conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8") 
cursor = conn.cursor()  
#写入  
sql = "insert into user(name,created) values(%s,%s)"  
param = ("aaa",int(time.time()))  
n = cursor.execute(sql,param)  
print n  
#更新  
sql = "update user set name=%s where id=3"  
param = ("bbb")  
n = cursor.execute(sql,param)  
print n  
#查询  
n = cursor.execute("select * from user")  
for row in cursor.fetchall():  
  for r in row:  
    print r  
#删除  
sql = "delete from user where name=%s"  
param =("aaa")  
n = cursor.execute(sql,param)  
print n  
cursor.close()  
#关闭  
conn.close()  
Copy after login

基本的使用如上,还是很简单的,进一步使用还没操作,先从网上找点资料放上来,以备后续查看

1.引入MySQLdb库

复制代码 代码如下:

import MySQLdb

2.和数据库建立连接

复制代码 代码如下:

conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")


提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.

比较常用的参数包括
host:数据库主机名.默认是用本地主机.
user:数据库登陆名.默认是当前用户.
passwd:数据库登陆的秘密.默认为空.
db:要使用的数据库名.没有默认值.
port:MySQL服务使用的TCP端口.默认是3306.
charset:数据库编码.

更多关于参数的信息可以查这里
http://mysql-python.sourceforge.net/MySQLdb.html

然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚

3.执行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条.

下面的代码是一个完整的例子.

#使用sql语句,这里要接收的参数都用%s占位符.要注意的是,无论你要插入的数据是什么类型,占位符永远都要用%s 
sql="insert into cdinfo values(%s,%s,%s,%s,%s)" 
#param应该为tuple或者list 
param=(title,singer,imgurl,url,alpha) 
#执行,如果成功,n的值为1 
n=cursor.execute(sql,param) 
#再来执行一个查询的操作 
cursor.execute("select * from cdinfo") 
#我们使用了fetchall这个方法.这样,cds里保存的将会是查询返回的全部结果.
#每条结果都是一个tuple类型的数据,这些tuple组成了一个tuple 
cds=cursor.fetchall() 
#因为是tuple,所以可以这样使用结果集 
print cds[0][3] 
#或者直接显示出来,看看结果集的真实样子 
print cds 
#如果需要批量的插入数据,就这样做 
sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)" 
#每个值的集合为一个tuple,整个参数集组成一个tuple,或者list 
param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2)) 
#使用executemany方法来批量的插入数据.这真是一个很酷的方法! 
n=cursor.executemany(sql,param) 
Copy after login

4.关闭数据库连接

需要分别的关闭指针对象和连接对象.他们有名字相同的方法
cursor.close()
conn.close()

四步完成,基本的数据库操作就是这样了.下面是两个有用的连接
MySQLdb用户指南: http://mysql-python.sourceforge.net/MySQLdb.html
MySQLdb文档: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html

5 编码(防止乱码)

需要注意的点:

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') 
Copy after login

注:MySQL的配置文件设置也必须配置成utf8

设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf):

<!--[endif]-->
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8
<!--[endif]-->
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the &lt;width&gt; and &lt;height&gt; tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

What is the process of converting XML into images? What is the process of converting XML into images? Apr 02, 2025 pm 08:24 PM

To convert XML images, you need to determine the XML data structure first, then select a suitable graphical library (such as Python's matplotlib) and method, select a visualization strategy based on the data structure, consider the data volume and image format, perform batch processing or use efficient libraries, and finally save it as PNG, JPEG, or SVG according to the needs.

See all articles