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脚本吧(包括创建表、插入数据、从文件读取并插入数据、查询数据等):

 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数据库的更多相关文章

  1. Python学习笔记9-Python 链接MySql数据库

    Python 链接MySql数据库,方法很简单: 首先需要先 安装一个MySql链接插件:MySQL-python-1.2.3.win-amd64-py2.7.exe 下载地址:http://dev. ...

  2. Tomcat通过JNDI方式链接MySql数据库

    原文:Tomcat通过JNDI方式链接MySql数据库 拷贝MySQL的JDBC驱动到Tomcat的lib路径下 配置全局数据源或者单个Web应用的局部数据源 局部数据源 在Tomcat的conf/C ...

  3. C# 链接MySql数据库

    C# 链接MySql数据库只得注意的几点: 1.C#链接MySql数据库要在网上下载一个mysql-connector-net-6.0.4-noinstall.rar  这里面放的都是一堆dll .将 ...

  4. 写给小白的JAVA链接MySQL数据库的步骤(JDBC):

    作为复习总结的笔记,我罗列了几个jdbc步骤,后边举个简单的例子,其中的try块请读者自行处理. /* * 1.下载驱动包:com.mysql.jdbc.Driver;网上很多下载资源,自己找度娘,此 ...

  5. Java链接MySQL数据库的用配置文件和不用配置文件的代码

    1.利用配置文件(db.properties)链接MySQL数据库 package tool; import java.io.FileInputStream;import java.sql.Conne ...

  6. SQLServer 远程链接MySql数据库详解

    SQLServer 远程链接MySql数据库详解 by:授客 QQ:1033553122 测试环境: Microsoft Windows XP Professional 版本2000 Service ...

  7. Java基于jdbc链接mysql数据库步骤示列

    用JDBC来链接MYSQL数据库,基本步骤都大同小异,只不过不同的数据库之间的URL地址有些不同.其基本步骤可分为以下几点: 1.加载相应的数据库的JDBC驱动程序. 2.利用驱动管理器DriverM ...

  8. Python3连接MySQL数据库实战

    Python3连接MySQL数据库实战 第三方库 :pymysql 数据库连接 def connect(): try: #建立数据库连接,从左至右参数依次为 # ip地址 我用的是云端数据库 如果为本 ...

  9. jmeter链接mysql数据库

    一.下载与MySQL对应的jar包 1.1.查询MySQL的版本, 命令语句 :SELECT VERSION(); 1.2.MySQL官网下载jar包 ,https://downloads.mysql ...

随机推荐

  1. .net使用memcached

    Windows中memached安装 -------------服务器端配置 1>开始>运行:CMD(确定) 2>cd C:\memcached(回车) 3>memcached ...

  2. 重建二叉树_C++

    一.题目背景 给定一个二叉树的前序和中序遍历,求出它的后序遍历 二叉树的遍历可参考 http://blog.csdn.net/fansongy/article/details/6798278/ 二.算 ...

  3. 在floodlight源码的基础上添加一个新的module并正确运行

    1.在src/main/java目录下新建一个package,目录结构如下: 2.在新建的package下,新建一个class,名字就是自定义的module,接下来implements想实现的serv ...

  4. c/c++类型转换相关总结

    在c语言中存在两种类型转换:显式类型转换和隐式类型转换: 显示类型转换:在类型前加上(type)变量,对变量进行的转换,程序员自己显式添加: char *ptra = (char*)ptrb; voi ...

  5. 加密中的salt是啥意思

    今天在stackoverflow上查看python的md5的问题,提到,除了简单的加密外,还可以加入一点salt 啥意思?百度一下看到:(https://zhidao.baidu.com/questi ...

  6. hdu 1558(计算几何+并查集)

    Segment set Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  7. HDU 6038.Function-数学+思维 (2017 Multi-University Training Contest - Team 1 1006)

    学长讲座讲过的,代码也讲过了,然而,当时上课没来听,听代码的时候也一脸o((⊙﹏⊙))o 我的妈呀,语文不好是硬伤,看题意看了好久好久好久(死一死)... 数学+思维题,代码懂了,也能写出来,但是还是 ...

  8. HDU 6112.今夕何夕-蔡勒公式 (2017"百度之星"程序设计大赛 - 初赛(A)1005)

    1005:今夕何夕 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)     Probl ...

  9. HDU 6108.小C的倍数问题 (2017"百度之星"程序设计大赛 - 初赛(A)1001)

    补完题?不存在的. 这么久了,还是一条咸鱼,看一堆乱七八糟的东西,写一堆没用的水题,一点进步都没有,还是那么菜,菜的掉渣. 这个百毒之星初赛A还会写两道最简单的水题,初赛B一点也不会,菜的难过... ...

  10. 51nod 1096 距离之和最小【中位数】

    1096 距离之和最小 基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题  收藏  关注 X轴上有N个点,求X轴上一点使它到这N个点的距离之和最小,输出这个最小的距离 ...