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

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 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

How to access DeepSeekapi - DeepSeekapi access call tutorial How to access DeepSeekapi - DeepSeekapi access call tutorial Mar 12, 2025 pm 12:24 PM

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once

Monitoring Redis Droplets Using Redis Exporter Service Monitoring Redis Droplets Using Redis Exporter Service Jan 06, 2025 am 10:19 AM

Effective monitoring of Redis databases is essential for maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a robust utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you establish a monitoring solution seamlessly. By following this tutorial, you’ll achieve a fully operational monitoring setup to effectively monitor the performance metrics of your Redis database.

See all articles