使用MySQL Connector/Python操作MySQL、MariaDB数据库
因目前MySQLdb并不支持python3.x,而MySQL官方已经提供了MySQL连接器,而且已经有支持Python3.x的版本,所以使用MySQL Connector/Python来操作数据库
测试环境:
win7 32位
JetBrains PyCharm 4.0.5
Python版本:Python 3.3.2
Windows (x86, 32-bit), MSI Installer Python 3.3
下载地址:http://dev.mysql.com/downloads/connector/python/
网盘下载地址:http://pan.baidu.com/s/1kTRqRht
dbconfig.conf配置:
[DATABASE]
host = 192.168.1.102
port = 3306
user = testacc
passwd = test1234
db = 1dcq
charset = utf8
代码实践
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
import mysql.connector
from mysql.connector import errorcode
import configparser
import sys
from datetime import date, datetime, timedelta
class GetDB:
'''配置数据库IP,端口等信息,获取数据库连接'''
def __init__(self, ini_file):
config = configparser.ConfigParser()
# 从配置文件中读取数据库服务器IP、域名,端口
config.read(ini_file)
self.host = config['DATABASE']['host']
self.port = config['DATABASE']['port']
self.user = config['DATABASE']['user']
self.passwd = config['DATABASE']['passwd']
self.db = config['DATABASE']['db']
self.charset = config['DATABASE']['charset']
def get_conn(self):
try:
conn = mysql.connector.connect(host=self.host, port=self.port, user=self.user, password=self.passwd, database=self.db, charset=self.charset)
return conn
except Exception as e:
print('%s', e)
sys.exit()
# 创建数据库
def create_database(self, cursor, db_name):
try:
cursor.execute("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARSET 'utf8'".format(db_name))
except mysql.connector.Error as err:
print('Failed creating database: {}'.format(err))
exit(1)
# 切换数据库
def use_database(self, cursor, db_name):
try:
cursor.execute('USE {}'.format(db_name))
except mysql.connector.Error as err:
if err.errno == errorcode.ER_BAD_DB_ERROR: # ER_BAD_DB_ERROR 未知数据库
self.create_database(cursor, db_name)
cursor.execute('USE {}'.format(db_name))
else:
print(err)
exit(1)
# 创建表-批量创建(如果表直接存在依赖关系,但是执行时未对传入的tables字典参数的项进行排序,可能无法创建成功)
def create_table(self, cursor, tables):
for table_name, table_ddl in tables.items():
try:
print("Creating table {}:".format(table_name), end='')
cursor.execute(table_ddl)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print('OK')
# 创建表
def create_table(self, cursor, table_ddl):
try:
print('Result of creating table:', end='')
cursor.execute(table_ddl)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print('OK')
# 插入数据
def insert_data(self, cursor, insert_ddl, insert_data):
try:
cursor.execute(insert_ddl, insert_data)
print('insert data into table success')
except mysql.connector.Error as err:
print('insert data into table failed')
print(err)
# 查询数据
def query_data(self, cursor, query_ddl, query_data=None):
try:
if query_data:
cursor.execute(query_ddl, query_data)
else:
cursor.execute(query_ddl)
for row in cursor:
print(row)
except mysql.connector.Error as err:
print(err)
if __name__ == '__main__':
db = GetDB('./dbconfig.conf')
dbconn = db.get_conn()
cursor = dbconn.cursor()
DB_NAME = 'employees'
TABLES = {}
TABLES['employees'] = (
"CREATE TABLE `employees` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `birth_date` date NOT NULL,"
" `member_name` varchar(14) NOT NULL,"
" `gender` enum('M','F') NOT NULL,"
" `hire_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB")
TABLES['departments'] = (
"CREATE TABLE `departments` ("
" `dept_no` int(11) NOT NULL,"
" `dept_name` varchar(40) NOT NULL,"
" PRIMARY KEY (`dept_no`), UNIQUE KEY `dept_name`(`dept_name`)"
") ENGINE=InnoDB")
db.create_database(cursor, 'testdb')
db.use_database(cursor, DB_NAME)
#db.create_table(cursor, TABLES)
print('creating table employees')
db.create_table(cursor, TABLES['employees'])
print('creating table departments')
db.create_table(cursor, TABLES['departments'])
tomorrow = datetime.now().date() + timedelta(days=1)
add_employee = ("INSERT INTO employees "
"(member_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s)")
add_departments = ("INSERT INTO departments "
"(dept_no, dept_name) "
"VALUES (%(dept_no)s, %(dept_name)s)")
data_employee = ('Geert', tomorrow, 'M', date(1977, 6, 14))
# Insert new employee
db.insert_data(cursor, add_employee, data_employee)
# Insert departments information
emp_no = cursor.lastrowid
data_departments = {
'dept_no': emp_no,
'dept_name': 'computer'+ str(emp_no)
}
db.insert_data(cursor, add_departments, data_departments)
# 使插入数据操作生效
try:
dbconn.commit()
except Exception as e:
print(e)
dbconn.rollback()
query = ("SELECT member_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = date(2015, 1, 1)
hire_end = date(2016, 1, 10)
db.query_data(cursor, query,(hire_start, hire_end))
# 关闭游标
cursor.close()
# 关闭数据库连接
dbconn.close()
注:其它操作和MYSQLdb类似,不再赘述,烦请参考文章:Python2.7操作Mariadb、Mysql数据库简介
运行结果:
参考连接:
http://dev.mysql.com/doc/connector-python/en/
http://dev.mysql.com/doc/connector-python/en/connector-python-examples.html