PYTHON3连接MYSQL数据库
http://smilejay.com/2013/03/python3-mysql-connector/
Python 2.x 上连接MySQL的库倒是不少的,其中比较著名就是MySQLdb(Django项目都使用它;我也在开发测试系统时也使用过),见:http://sourceforge.net/projects/mysql-python/
不过,目前MySQLdb并不支持python3.x,网上找了一些方法,后来我还是偶然发现MySQL官方已经提供了MySQL连接器,而且已经有支持Python3.x的版本了。MySQL Connector/Python, a self-contained Python driver for communicating with MySQL servers. 这个用起来还是感觉比较顺手的。
关于MySQL Connector/Python的各种介绍、安装、API等文档,还是参考官网吧:http://dev.mysql.com/doc/connector-python/en/index.html
(注意:安装程序将关于MySQL Connnector的python2的源文件复制到了python3库的位置(运行时会报语法错误),我就直接手动复制了其中python3/目录下的文件过去就解决。)
另外,Python3.x连接MySQL的其他方案有:oursql, PyMySQL, myconnpy 等,参考如下链接:
http://packages.python.org/oursql/
https://github.com/petehunt/PyMySQL/
https://launchpad.net/myconnpy
下面只是贴一个试用 MySQL Connector/Python 的Python脚本吧(包括创建表、插入数据、从文件读取并插入数据、查询数据等):
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#!/usr/bin/python3
# a sample to use mysql-connector for python3
# see details from http://dev.mysql.com/doc/connector-python/en/index.html
import mysql.connector
import sys, os
user = 'root'
pwd = '123456'
host = '127.0.0.1'
db = 'test'
data_file = 'mysql-test.dat'
create_table_sql = "CREATE TABLE IF NOT EXISTS mytable ( \
id int(10) AUTO_INCREMENT PRIMARY KEY, \
name varchar(20), age int(4) ) \
CHARACTER SET utf8"
insert_sql = "INSERT INTO mytable(name, age) VALUES ('Jay', 22 ), ('杰', 26)"
select_sql = "SELECT id, name, age FROM mytable"
cnx = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
cursor = cnx.cursor()
try:
cursor.execute(create_table_sql)
except mysql.connector.Error as err:
print("create table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
try:
cursor.execute(insert_sql)
except mysql.connector.Error as err:
print("insert table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
if os.path.exists(data_file):
myfile = open(data_file)
lines = myfile.readlines()
myfile.close()
for line in lines:
myset = line.split()
sql = "INSERT INTO mytable (name, age) VALUES ('{}', {})".format(myset[0], myset[1])
try:
cursor.execute(sql)
except mysql.connector.Error as err:
print("insert table 'mytable' from file 'mysql-test.dat' -- failed.")
print("Error: {}".format(err.msg))
sys.exit()
try:
cursor.execute(select_sql)
for (id, name, age) in cursor:
print("ID:{} Name:{} Age:{}".format(id, name, age))
except mysql.connector.Error as err:
print("query table 'mytable' failed.")
print("Error: {}".format(err.msg))
sys.exit()
cnx.commit()
cursor.close()
cnx.close()
|
另外,最后再贴一个使用MySQLdb的python2.x代码示例吧:
Python
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#!/usr/bin/python2.7
# coding=utf-8
import MySQLdb
import sys
host = 'localhost'
user = 'root'
pwd = '123456' # to be modified.
db = 'test'
if __name__ == '__main__':
conn = MySQLdb.connect(host, user, pwd, db, charset='utf8');
try:
conn.ping()
except:
print 'failed to connect MySQL.'
sql = 'select * from mytable where id = 2'
cur = conn.cursor()
cur.execute(sql)
row = cur.fetchone()
# print type(row)
for i in row:
print i
cur.close()
conn.close()
sys.exit()
|
PYTHON3连接MYSQL数据库的更多相关文章
- Python3连接MySQL数据库实战
Python3连接MySQL数据库实战 第三方库 :pymysql 数据库连接 def connect(): try: #建立数据库连接,从左至右参数依次为 # ip地址 我用的是云端数据库 如果为本 ...
- python3连接MySQL数据库实例
#python3连接MySQL实例 import pymysql """导入连接MySQL需要的包,没有安装pymysql需要先安装 使用命令行切换到python的安装路 ...
- 【python】python3连接mysql数据库
一.安装pymysql 详见http://www.runoob.com/python3/python3-mysql.html 二.连接mysql数据库 db = pymysql.connect( #连 ...
- python3 连接mysql数据库
准备工作: 1.在本地虚拟机172.16.0.115上安装mysql,并设置权限如下 mysql> grant all privileges on *.* to root@"%&quo ...
- linux下python3连接mysql数据库
python语言的3.x完全不向前兼容,导致我们在python2.x中可以正常使用的库,到了python3就用不了了.比如说mysqldb 1.安装pymysql pymysql就是作为python3 ...
- python3.4怎么连接mysql pymysql连接mysql数据库
本文介绍了python3 4连接mysql数据库的方法,在python3 4中使用原来python2 7的mysqldb已不能连接mysql数据库了,可以使用pymysql. 在python3.4 ...
- Python3.x使用PyMysql连接MySQL数据库
Python3.x使用PyMysql连接MySQL数据库 由于Python3.x不向前兼容,导致Python2.x中的很多库在Python3.x中无法使用,例如Mysqldb,我前几天写了一篇博客Py ...
- Python3.x:使用PyMysql连接Mysql数据库
Python3.x:使用PyMysql连接Mysql数据库 Python3.x完全不向前兼容,导致Python2.x中可以正常使用的库,到了Python3就用不了: 比如说mysqldb,目前MySQ ...
- Python3:Django连接Mysql数据库时出错,'Did you install mysqlclient or MySQL-python?'
Python3:Django连接Mysql数据库时出错,'Did you install mysqlclient or MySQL-python?' 一.原因 因为Python版本问题,MySQLdb ...
随机推荐
- VS2013 好用的插件
切换到vs2013上有些时间了,以下是我个人认为比较好的插件. Resharper 神器中的神器,提升编码效率的第一神器,附带提高编码能力:除去臃肿的体积,堪称完美: Productivity Pow ...
- Redis操作命令总结
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/118.html?1455860089 一.key pattern 查询相应 ...
- Atitit J2EE平台相关规范--39个 3.J2SE平台相关规范--42个
Atitit J2EE平台相关规范--39个 3.J2SE平台相关规范--42个 2.J2EE平台相关规范--39个5 XML Parsing Specification16 J2EE Conne ...
- Atitit 开发2d游戏的技术选型attilax总结
Atitit 开发2d游戏的技术选型attilax总结 1.1. 跨平台跨平台:一定要使用跨平台的gui技术,目前最好的就是h5(canvas,webgl,dom) +js了..1 1.2. 游戏前后 ...
- 使用 flow.ci 实现 Android 自动化测试与持续集成
在上篇文章--如何实现 Android 应用的持续部署中,我们使用的是 flow.ci + Github + fir.im 实现 Android 应用的持续部署.对于 Android 开发者,他们可能 ...
- BugHD for JavaScript上线,轻松收集前端 Error
从收集 APP 崩溃信息到全面收集网站出现的 Error,现在的 BugHD 变得更加强大.目前,BugHD JS Error 收集功能 已正式上线,前端 er 们不用再面对一堆 Bug 无处下手. ...
- Findbugs介绍及使用方法
1. 简介 Findbugs 是一个静态分析工具,它检查类或者 JAR 文件,将字节码与一组缺陷模式进行对比以发现可能的问题.利用这个工具,就可以在不实际运行程序的情况对软件进行分析.它可以帮助改 ...
- KnockoutJS 3.X API 第五章 高级应用(2) 控制后代绑定
注意:这是一种高级技术,通常仅在创建可重用绑定的库时使用. 默认情况下,绑定仅影响它们应用到的元素. 但是如果你想影响所有的后代元素呢? 为此,只需从绑定的init函数中返回{controlsDesc ...
- Html与CSS快速入门02-HTML基础应用
这部分是html细节知识的学习. 快速入门系列--HTML-01简介 快速入门系列--HTML-02基础元素 快速入门系列--HTML-03高级元素和布局 快速入门系列--HTML-04进阶概念 示例 ...
- vc操作windows防火墙的方法
收藏该地址,以备不时之需. http://msdn.microsoft.com/en-us/library/aa364726.aspx