当前位置:Gxlcms > mysql > Python3连接MySQL数据库

Python3连接MySQL数据库

时间:2021-07-01 10:21:17 帮助过:28人阅读

Python 2.x 上连接MySQL的库倒是不少的,其中比较著名就是MySQLdb(Django项目都使用它;我也在开发测试系统时也使用过),见:http://sourceforge.net/projects/mysql-python/ 不过,目前MySQLdb并不支持python3.x,网上找了一些方法,后来我还是偶然发现My

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. #!/usr/bin/python3
  2. # a sample to use mysql-connector for python3
  3. # see details from http://dev.mysql.com/doc/connector-python/en/index.html
  4. import mysql.connector
  5. import sys, os
  6. user = 'root'
  7. pwd = '123456'
  8. host = '127.0.0.1'
  9. db = 'test'
  10. data_file = 'mysql-test.dat'
  11. create_table_sql = "CREATE TABLE IF NOT EXISTS mytable ( \
  12. id int(10) AUTO_INCREMENT PRIMARY KEY, \
  13. name varchar(20), age int(4) ) \
  14. CHARACTER SET utf8"
  15. insert_sql = "INSERT INTO mytable(name, age) VALUES ('Jay', 22 ), ('杰', 26)"
  16. select_sql = "SELECT id, name, age FROM mytable"
  17. cnx = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
  18. cursor = cnx.cursor()
  19. try:
  20. cursor.execute(create_table_sql)
  21. except mysql.connector.Error as err:
  22. print("create table 'mytable' failed.")
  23. print("Error: {}".format(err.msg))
  24. sys.exit()
  25. try:
  26. cursor.execute(insert_sql)
  27. except mysql.connector.Error as err:
  28. print("insert table 'mytable' failed.")
  29. print("Error: {}".format(err.msg))
  30. sys.exit()
  31. if os.path.exists(data_file):
  32. myfile = open(data_file)
  33. lines = myfile.readlines()
  34. myfile.close()
  35. for line in lines:
  36. myset = line.split()
  37. sql = "INSERT INTO mytable (name, age) VALUES ('{}', {})".format(myset[0], myset[1])
  38. try:
  39. cursor.execute(sql)
  40. except mysql.connector.Error as err:
  41. print("insert table 'mytable' from file 'mysql-test.dat' -- failed.")
  42. print("Error: {}".format(err.msg))
  43. sys.exit()
  44. try:
  45. cursor.execute(select_sql)
  46. for (id, name, age) in cursor:
  47. print("ID:{} Name:{} Age:{}".format(id, name, age))
  48. except mysql.connector.Error as err:
  49. print("query table 'mytable' failed.")
  50. print("Error: {}".format(err.msg))
  51. sys.exit()
  52. cnx.commit()
  53. cursor.close()
  54. cnx.close()

另外,最后再贴一个使用MySQLdb的python2.x代码示例吧:

  1. #!/usr/bin/python2.7
  2. # coding=utf-8
  3. import MySQLdb
  4. import sys
  5. host = 'localhost'
  6. user = 'root'
  7. pwd = '123456' # to be modified.
  8. db = 'test'
  9. if __name__ == '__main__':
  10. conn = MySQLdb.connect(host, user, pwd, db, charset='utf8');
  11. try:
  12. conn.ping()
  13. except:
  14. print 'failed to connect MySQL.'
  15. sql = 'select * from mytable where id = 2'
  16. cur = conn.cursor()
  17. cur.execute(sql)
  18. row = cur.fetchone()
  19. # print type(row)
  20. for i in row:
  21. print i
  22. cur.close()
  23. conn.close()
  24. sys.exit()

Original article: Python3连接MySQL数据库

©2013 笑遍世界. All Rights Reserved.

人气教程排行