Home Database Mysql Tutorial 用Python操作Mysql和中文有关问题

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

Jun 07, 2016 pm 04:15 PM
mysql python Chinese operate

用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 #注意大小写!!  
Copy after login

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

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



创建数据库,创建表,插入数据,插入多条数据
#!/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(); 
Copy after login



查询和插入的流程差不多,只是多了一个得到查询结果的步骤
#!/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() 
Copy after login



中文问题:
#!/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()
Copy after login
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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Laravel vs. Python (with Frameworks): A Comparative Analysis Laravel vs. Python (with Frameworks): A Comparative Analysis Apr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

See all articles