python 3.6 +pyMysql 操作mysql数据库

版本信息:python:3.6  mysql:5.7  pyMysql:0.7.11

################################################################# #author: 陈月白 #_blogs: http://www.cnblogs.com/chenyuebai/ ################################################################# 
# -*- coding: utf-8 -*-

class MysqlTools():
    """
    连接mysql    库、表操作
    """
    def __init__(self,host,dbname,user,passwd,charset="utf8"):
        self.host = host
        self.dbname = dbname
        self.user = user
        self.passwd = passwd
        self.charset = charset

    def connectMysqlDatabase(self):
        """连接db"""
        try:
            #连接db
            connect = pymysql.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.dbname,charset=self.charset)
            cursor = connect.cursor()
            databaseConnectInfo = self.user + "@" + "self.host" + "/" +  self.dbname
            print("INFO:connect database %s success."%databaseConnectInfo)
            return connect,cursor
        except:
            traceback.print_exc()
            print("ERROR:FUNCTION connectMysqlDatabase connect mysql database failed.")

    def executeSqlLine(self,sqlLine):
        """执行单条sql语句"""
        if sqlLine and isinstance(sqlLine,str):
            print("INFO:now start connect mysql dababase.")
            connect,cursor = self.connectMysqlDatabase()
            executeResult = ""
            try:
                #游标执行sql
                cursor.execute(sqlLine)
                executeResult = cursor.fetchall()       #获取所有执行结果
                cursor.close()                          #关闭游标
                connect.commit()                        #确认提交
                print("INFO:execute sql sucess. sqlLine = ", sqlLine)
            except Exception as e:
                print("ERROR:execute sql failed.errorInfo =",e)
                print("ERROR:FUNCTION executeSql execute failed.sqlLine =",sqlLine)
                connect.rollback()                      #回滚db
                return str(e) + "    sqlLine = " + sqlLine
            #断开连接
            connect.close()
            print("INFO:connect closed.\n")
            return executeResult
        else:
            print("ERROR:param sqlLine is empty or type is not str.sqlLine = ",sqlLine)

    def executeBatchSql(self,sqlList):
        """
        批量执行sql
        exp:    executeBatchSql([sql_1,
                                sql_2,
                                sql_3,
                                ......
                                ])
        """
        finalResultList = []
        if sqlList:
            for sql in sqlList:
                executeResult = self.executeSqlLine(sql)
                finalResultList.append(executeResult)
        else:
            print("ERROR:param sqlList is empty.")
        return finalResultList

测试代码:

# -*- coding: utf-8 -*-
from my_code.work_tools import WorkTools

mysql = WorkTools.MysqlTools("localhost","testdbname","rootuername","passwd")
#执行单行sql
ret1 = mysql.executeSqlLine("show databases")

#批量执行
ret2 = mysql.executeBatchSql([
                            "show databases",
                            "show tables",
                            "update students_info set name = ‘王大花D‘ where id = 2",
                            "select * from students_info",
                            "error sql test"  #异常sql测试
                              ])

print("ret1 = ",ret1)
print("---------------------")
for i in ret2:
    print(i)

测试表:

执行结果:

ret1 =  ((‘information_schema‘,), (‘mysql‘,), (‘performance_schema‘,), (‘sakila‘,), (‘sys‘,), (‘testdb‘,), (‘world‘,))
---------------------
((‘information_schema‘,), (‘mysql‘,), (‘performance_schema‘,), (‘sakila‘,), (‘sys‘,), (‘testdb‘,), (‘world‘,))
((‘students_info‘,),)
()
((1, ‘陈月白‘, ‘male‘, 25, ‘20176666‘, ‘1351234‘), (2, ‘王大花D‘, ‘female‘, 19, ‘19920816‘, ‘10086‘), (3, ‘李强新‘, ‘male‘, 18, ‘19941025‘, ‘10000‘), (4, ‘王鹏‘, ‘male‘, 20, ‘19970405‘, ‘10010‘), (5, ‘钟齐‘, ‘male‘, 22, ‘19970420‘, ‘123456789‘), (6, ‘王大花‘, ‘female‘, 15, ‘19981024‘, ‘12345678‘))
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘error sql test‘ at line 1")    sqlLine = error sql test

时间: 2024-10-02 21:30:30

python 3.6 +pyMysql 操作mysql数据库的相关文章

如何使用python中的pymysql操作mysql数据库

操作流程 导入模块 from pymsql import * 创建connect链接 conn = connect(host, port, user, password, database, charset) 获取游标对象 cs1 = conn.cursor() 执行语句 count = cs1.execute(SQL语句) 查看执行的语句 cs1.fetchone() # 返回元组结构的一条数据 查看多条语句 cs1.fetchmany(3) # 取出3个数据元组套元组,不写数量就只取一个 查

PyMySQL操作mysql数据库(py3必学)

一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. > pip install  PyMySQL 二,创建MySQL表 执行下面的SQL语句,创建一张users 表. CREATE TABLE `users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `email` VARCHAR(255) COLLATE u

Python MySQLdb模块连接操作mysql数据库实例_python

mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法.python操作数据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/有下载和文档. 由于python的数据库模块有专门的数据库模块的规范,所以,其实不管使用哪种数据库的方法都大同小异的,这里就给出一段示范的代码: #-*- encoding: gb2312 -*- import os, sys, string impo

flask + pymysql操作Mysql数据库

安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql 安装Mysql数据库 from flask.ext.sqlalchemy import SQLAlchemy from flask import Flask '''配置数据库''' app = Flask(__name__) app.config['SECRET_KEY'] ='hard to guess' # 这里登陆的是root用户,要填上自己的密码,MySQL

用pymysql操作MySQL数据库

工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 # 参数2:登陆数据库的用户名 # 参数3:登陆数据库的密码 # 参数4:要连接的数据库 # 参数5:字符编码 db = pymysql.connect( 'localhost', 'root', '123456', 'school', charset = 'utf8' ) # 增删改插操作 #

使用PyMySQL操作mysql数据库

适用环境 python版本 >=2.6或3.3 mysql版本>=4.1 安装 可以使用pip安装也可以手动下载安装. 使用pip安装,在命令行执行如下命令: 1 pip install PyMySQL 手动安装,请先下载.下载地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X. 其中的X.X是版本(目前可以获取的最新版本是0.6.6). 下载后解压压缩包.在命令行中进入解压后的目录,执行如下的指令: 1 python setup

【python深入5】操作mysql数据库、语言类型

1)mysql基本操作 show?databases;??//查看当前数据库 use?mysql;??//进入mysql库 show?tables;??//查看mysql库中的表 create?table?user?(name?varchar(20),password?varchar(20));??//创建user表,包含name.password字段 insert?into?user?values('Tom','1321');??//向user表里插入若干条数据 select?*?from?u

Python学习笔记-pyMySQL连接MySQL数据库

下载pyMySQL模块包 [[email protected] ~]# python36 -m pip install pyMySQL Collecting pyMySQL   Downloading PyMySQL-0.7.11-py2.py3-none-any.whl (78kB)     100% |################################| 81kB 8.9kB/s  Installing collected packages: pyMySQL Successfu

Python操作mysql数据库出现pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check

今天在用Python操作mysql数据库出现pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check报错 "SELECT Failure_code,describe from failure_occur_now order by ID DESC LIMIT 1“黄色区域为报错的位置仔细查找,发现没有语法错误啊,后面将,describe删掉不报错了,原来describe应该是Mysq