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

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 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

 

 

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
18
分享
相关文章
Python中使用MySQL模糊查询的方法
本文介绍了两种使用Python进行MySQL模糊查询的方法:一是使用`pymysql`库,二是使用`mysql-connector-python`库。通过这两种方法,可以连接MySQL数据库并执行模糊查询。具体步骤包括安装库、配置数据库连接参数、编写SQL查询语句以及处理查询结果。文中详细展示了代码示例,并提供了注意事项,如替换数据库连接信息、正确使用通配符和关闭数据库连接等。确保在实际应用中注意SQL注入风险,使用参数化查询以保障安全性。
python脚本:连接数据库,检查直播流是否可用
【10月更文挑战第13天】本脚本使用 `mysql-connector-python` 连接MySQL数据库,检查 `live_streams` 表中每个直播流URL的可用性。通过 `requests` 库发送HTTP请求,输出每个URL的检查结果。需安装 `mysql-connector-python` 和 `requests` 库,并配置数据库连接参数。
152 68
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
455 15
探索Python中的异步编程:从asyncio到异步数据库操作
在这个快节奏的技术世界里,效率和性能是关键。本文将带你深入Python的异步编程世界,从基础的asyncio库开始,逐步探索到异步数据库操作的高级应用。我们将一起揭开异步编程的神秘面纱,探索它如何帮助我们提升应用程序的性能和响应速度。
使用 Python 解析火狐浏览器的 SQLite3 数据库
本文介绍如何使用 Python 解析火狐浏览器的 SQLite3 数据库,包括书签、历史记录和下载记录等。通过安装 Python 和 SQLite3,定位火狐数据库文件路径,编写 Python 脚本连接数据库并执行 SQL 查询,最终输出最近访问的网站历史记录。
86 4
SQL与Python集成:数据库操作无缝衔接22.bijius.com
自动化数据预处理:使用Python库(如Pandas)自动清洗、转换和准备数据,为机器学习模型提供高质量输入。 实时数据处理:集成Apache Kafka或Amazon Kinesis等流处理系统,实现实时数据更新和分析。
Mysql学习笔记(四):Python与Mysql交互--实现增删改查
如何使用Python与MySQL数据库进行交互,实现增删改查等基本操作的教程。
104 1
轻量级数据库的利器:Python 及其内置 SQLite 简介
轻量级数据库的利器:Python 及其内置 SQLite 简介
112 3
SQL与Python集成:数据库操作无缝衔接
在开始之前,确保你已经安装了必要的Python库,如`sqlite3`(用于SQLite数据库)或`psycopg2`(用于PostgreSQL数据库)。这些库提供了Python与SQL数据库之间的接口。
Maria DB Workbench支持哪些数据库引擎
【10月更文挑战第17天】Maria DB Workbench支持哪些数据库引擎
96 0

热门文章

最新文章