search
HomeDatabaseMysql Tutorial用Python操作Mysql和中文有关问题

用Python操作Mysql和中文问题 http://www.iteye.com/topic/573092 平时的主要编程语言是Java,开发时也主要用Mysql,经常为了测试,调试的目的需要操作数据库,比如备份,插入测试数据,修改测试数据,有些时候不能简单的用SQL就能完成任务,或都很好的完成任

用Python操作Mysql和中文问题
http://www.iteye.com/topic/573092
平时的主要编程语言是Java,开发时也主要用Mysql,经常为了测试,调试的目的需要操作数据库,比如备份,插入测试数据,修改测试数据,有些时候不能简单的用SQL就能完成任务,或都很好的完成任务,用Java写又有点太麻烦了,就想到了Python。Python语法简洁,不用编译,可以经较好的完成任务。今天看了下Python对Mysql的操作,做一下记录。

首先,安装需要的环境,Mysql和Python就不说了,必备的东西。
主要是安装的MySQLdb,可以去sf.net下载,具体地址是http://sourceforge.net/projects/mysql-python/
如果用Ubuntu,直接

ubuntu: sudo apt-get install python-mysqldb
Fedora19: sudo yum -y install MySQL-python


安装完成之后可以在Pyth
import MySQLdb #注意大小写!!  

如果不报错,就证明安装成功了,可能继续了

MySQLdb在Python中也就相当于JAVA中的MySQL的JDBC Driver,Python也有类似的数据接口规范Python DB API,MySQLdb就是Mysql的实现。操作也比较简单和其它平台或语言操作数据库一样,就是建立和数据库系统的连接,然后给数据库输入SQL,再从数据库获取结果。
先写一个最简单的,
创建一个数据库:
#!/usr/bin/env python  
#coding=utf-8  
###################################  
# @author migle  
# @date 2010-01-17  
##################################  
#MySQLdb 示例  
#  
##################################  
import MySQLdb  
  
#建立和数据库系统的连接  
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
  
#获取操作游标  
cursor = conn.cursor()  
#执行SQL,创建一个数据库.  
cursor.execute("""create database python """)  
  
#关闭连接,释放资源  
cursor.close(); 



创建数据库,创建表,插入数据,插入多条数据
#!/usr/bin/env python  
#coding=utf-8  
###################################  
# @author migle  
# @date 2010-01-17  
##################################  
#MySQLdb 示例  
#  
##################################  
import MySQLdb  
  
#建立和数据库系统的连接  
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
  
#获取操作游标  
cursor = conn.cursor()  
#执行SQL,创建一个数据库.  
cursor.execute("""create database if not exists python""")  
  
#选择数据库  
conn.select_db('python');  
#执行SQL,创建一个数据表.  
cursor.execute("""create table test(id int, info varchar(100)) """)  
  
value = [1,"inserted ?"];  
  
#插入一条记录  
cursor.execute("insert into test values(%s,%s)",value);  
  
values=[]  
  
  
#生成插入参数值  
for i in range(20):  
    values.append((i,'Hello mysqldb, I am recoder ' + str(i)))  
#插入多条记录  
  
cursor.executemany("""insert into test values(%s,%s) """,values);  
  
#关闭连接,释放资源  
cursor.close(); 



查询和插入的流程差不多,只是多了一个得到查询结果的步骤
#!/usr/bin/env python  
#coding=utf-8  
######################################  
#  
# @author migle  
# @date 2010-01-17  
#  
######################################  
#  
# MySQLdb 查询  
#  
#######################################  
  
import MySQLdb  
  
conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')  
  
cursor = conn.cursor()  
  
count = cursor.execute('select * from test')  
  
print '总共有 %s 条记录',count  
  
#获取一条记录,每条记录做为一个元组返回  
print "只获取一条记录:"  
result = cursor.fetchone();  
print result  
#print 'ID: %s   info: %s' % (result[0],result[1])  
print 'ID: %s   info: %s' % result   
  
#获取5条记录,注意由于之前执行有了fetchone(),所以游标已经指到第二条记录了,也就是从第二条开始的所有记录  
print "只获取5条记录:"  
results = cursor.fetchmany(5)  
for r in results:  
    print r  
  
print "获取所有结果:"  
#重置游标位置,0,为偏移量,mode=absolute | relative,默认为relative,  
cursor.scroll(0,mode='absolute')  
#获取所有结果  
results = cursor.fetchall()  
for r in results:  
    print r  
conn.close() 



中文问题:
#!/usr/bin/python
# coding=gbk    # 要设定这个,否在有问题

# 说明:数据库是utf-8_bin的格式

import sys
import requests
import re
import MySQLdb
from BeautifulSoup import BeautifulSoup


url = "http://sh.house.163.com/13/0929/09/99U877FR00073SDJ.html"
req = requests.get(url)
#print req.content
bp = BeautifulSoup(req.content)

title = bp.findAll(id=re.compile("h1title"))
endText = bp.findAll(id=re.compile("endText"));


#  以utf-8的格式读出来
#charset="utf8" 这里是GBK也没问题
conn = MySQLdb.connect(host="192.168.0.196", user="root", passwd="", db="python", charset="utf8")
cursor = conn.cursor()

# 从页面的iso-8895-1编码成GBK
values = [title[0].text.encode("iso-8859-1").decode("GBK"), endText[0].text.encode("iso-8859-1").decode("GBK")];
#values = ["好人".decode("gbk").encode("utf-8"), "好人".decode("gbk").encode("utf-8")];
cursor.execute("insert into test(title,text) value(%s,%s)", values)

cursor.close()
conn.close()
Statement
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
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),