Python使用MySQLConnector/Python操作MySQL、MariaDB数据库

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: Python使用MySQLConnector/Python操作MySQL、MariaDB数据库

使用MySQL Connector/Python操作MySQLMariaDB数据库

 


 

因目前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操作MariadbMysql数据库简介

 

运行结果:

 

 


 

参考连接:

http://dev.mysql.com/doc/connector-python/en/

http://dev.mysql.com/doc/connector-python/en/connector-python-examples.html

 

 

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。   相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情: https://www.aliyun.com/product/rds/mysql 
目录
相关文章
|
2月前
|
缓存 关系型数据库 BI
使用MYSQL Report分析数据库性能(下)
使用MYSQL Report分析数据库性能
121 3
|
2月前
|
关系型数据库 MySQL 分布式数据库
阿里云PolarDB云原生数据库收费价格:MySQL和PostgreSQL详细介绍
阿里云PolarDB兼容MySQL、PostgreSQL及Oracle语法,支持集中式与分布式架构。标准版2核4G年费1116元起,企业版最高性能达4核16G,支持HTAP与多级高可用,广泛应用于金融、政务、互联网等领域,TCO成本降低50%。
|
2月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS费用价格:MySQL、SQL Server、PostgreSQL和MariaDB引擎收费标准
阿里云RDS数据库支持MySQL、SQL Server、PostgreSQL、MariaDB,多种引擎优惠上线!MySQL倚天版88元/年,SQL Server 2核4G仅299元/年,PostgreSQL 227元/年起。高可用、可弹性伸缩,安全稳定。详情见官网活动页。
|
2月前
|
关系型数据库 分布式数据库 数据库
阿里云数据库收费价格:MySQL、PostgreSQL、SQL Server和MariaDB引擎费用整理
阿里云数据库提供多种类型,包括关系型与NoSQL,主流如PolarDB、RDS MySQL/PostgreSQL、Redis等。价格低至21元/月起,支持按需付费与优惠套餐,适用于各类应用场景。
|
2月前
|
SQL 关系型数据库 MySQL
Mysql数据恢复—Mysql数据库delete删除后数据恢复案例
本地服务器,操作系统为windows server。服务器上部署mysql单实例,innodb引擎,独立表空间。未进行数据库备份,未开启binlog。 人为误操作使用Delete命令删除数据时未添加where子句,导致全表数据被删除。删除后未对该表进行任何操作。需要恢复误删除的数据。 在本案例中的mysql数据库未进行备份,也未开启binlog日志,无法直接还原数据库。
|
2月前
|
关系型数据库 MySQL 数据库
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎
阿里云数据库RDS支持MySQL、SQL Server、PostgreSQL和MariaDB引擎,提供高性价比、稳定安全的云数据库服务,适用于多种行业与业务场景。
|
2月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
261 102
|
2月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
295 104
|
2月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
247 103
|
2月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
186 82