Python基础之Mysql

1.MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。

2.Python下MySQLdb安装。

  (1)先下载MySQLdb安装包,解压。

  (2)cmd以管理员身份运行,进行MySQLdb目录,将MySQLdb安装至Python下:python setup.py install

  PyMySqlUtil.py

#coding=utf-8

import pymysql

class PyMySqlUtil:
    
    def __init__(self,host,port,userName,userPwd,database):
        self._host=host
        self._port=port
        self._userName=userName
        self._userPwd=userPwd
        self._database=database
        
    #进行数据查询操作,返回元组
    def executeQuery(self,sql):
        conn = pymysql.connect(host=self._host,port= self._port,user = self._userName,passwd=self._userPwd,db=self._database)
        cursor = conn.cursor()
        cursor.execute(sql)
        result=cursor.fetchall()
        cursor.close()
        conn.close()
        return result
        
    #进行数据增、删、改操作
    def executeNoneQuery(self,sql):
        conn = pymysql.connect(host=self._host,port= self._port,user = self._userName,passwd=self._userPwd,db=self._database)
        cursor = conn.cursor()
        try:
            cursor.execute(sql)
            conn.commit()
        except:
            db.rollback()
        cursor.close()
        conn.close()
        
    

 

调用代码:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from PyMySqlUtil  import *
>>> db=PyMySqlUtil("localhost",3306,"root","root","dgcms")
>>> result=db.executeQuery("select * from blog")
>>> print(result)
((7, 'go', 'VB.NET'), (4, '  C#', 'RWRRWWW'), (6, 'object c', 'object c'), (5, 'python', 'haaaa'))
>>> 

 

posted on 2017-06-27 22:31  伈隨夢飛  阅读(183)  评论(0编辑  收藏  举报

导航