python 操作mysql数据库

python 操作mysql数据库,包括创建表,删除表,插入数据,删除数据,修改数据等操作。

# -*- coding: utf-8 -*-
import mysql.connector
import os

class MySqlDB:

  #是否打印sql
  print_sql = True

  #数据库连接
  mySql_Conn = None
  def __init__(self):
    '''初始化数据库连接'''
    self.mySql_Conn = self.get_Conn()


  def get_Conn(self):
    #return mysql.connector.connect(user='root', password='', database='test', use_unicode=True)
    return mysql.connector.connect(user='root', password='', database='python_test', charset='utf8')


  def commit(self):
    '''提交数据库事务'''
    if self.mySql_Conn is not None:
      self.mySql_Conn.commit()

  def get_Cursor(self):
    '''
     该方法是获取数据库的游标对象,参数为数据库的连接对象
     如果数据库的连接对象不为None,则返回数据库连接对象所创
     建的游标对象;否则返回一个游标对象,该对象是内存中数据
     库连接对象所创建的游标对象
    '''
    if self.mySql_Conn is not None:
      return self.mySql_Conn.cursor()
    else:
      return self.mySql_Conn.cursor()

  def close_Cursor(self,cursor):
    '''关闭数据库游标对象和数据库连接对象'''
    try:
      if cursor is not None:
        cursor.close()
    finally:
      if cursor is not None:
        cursor.close()

################################################################
#创建表,删除表操作
################################################################
  def create_Table(self, strSql):
    '''创建数据库表:'''
    if strSql is not None and strSql != '':
      cursor = self.get_Cursor()
      if self.print_sql:
        print('执行sql:[{}]'.format(strSql))
      cursor.execute(strSql)
      self.commit()
      print('创建数据库表成功!')
      self.close_Cursor(cursor)
    else:
      print('the [{}] is empty or equal None!'.format(strSql))


  def drop_Table(self,table):
    '''如果表存在,则删除表,如果表中存在数据的时候,使用该
    方法的时候要慎用!'''
    if table is not None and table != '':
      strSql = 'DROP TABLE IF EXISTS ' + table
      if self.print_sql:
        print('执行sql:[{}]'.format(strSql))
      cursor = self.get_Cursor()
      cursor.execute(strSql)
      self.commit()
      print('删除数据库表[{}]成功!'.format(table))
      self.close_Cursor(cursor)
    else:
      print('the [{}] is empty or equal None!'.format(strSql))

#####################################################################

#数据库操作
#####################################################################
  def insert_MultiData(self,strSql, data):
    '''插入数据'''
    if strSql is not None and strSql != '':
      if data is not None:
        cursor = self.get_Cursor()
        for d in data:
          if self.print_sql:
            print('执行sql:[{}],参数:[{}]'.format(strSql, d))
          cursor.execute(strSql, d)
          self.commit()
          self.close_Cursor(cursor)
    else:
      print('the [{}] is empty or equal None!'.format(strSql))

  def insert_Data(self,strSql):
    '''插入数据'''
    if strSql is not None and strSql != '':
      cursor = self.get_Cursor()
      print('执行sql:[{}]'.format(strSql))
      cursor.execute(strSql)
      self.commit()
      self.close_Cursor(cursor)

    else:
      print('the [{}] is empty or equal None!'.format(strSql))

  def get_All_Item(self,strSql):
    '''查询所有数据'''
    if strSql is not None and strSql != '':
      cursor = self.get_Cursor()
      if self.print_sql:
        print('执行sql:[{}]'.format(strSql))
      cursor.execute(strSql)
      listR = cursor.fetchall()
      self.close_Cursor(cursor)
      return listR

    else:
      print('the [{}] is empty or equal None!'.format(strSql))
      return None

  def get_One_Item(self,strSql, data):
    '''查询一条数据'''
    if strSql is not None and strSql != '':
      if data is not None:
        #Do this instead
        d = (data,)
        cursor = self.get_Cursor()
        if self.print_sql:
          print('执行sql:[{}],参数:[{}]'.format(strSql, data))
        cursor.execute(strSql, d)
        r = cursor.fetchall()
        if len(r) > 0:
          for e in range(len(r)):
          print(r[e])
        else:
          print('the [{}] equal None!'.format(data))
    else:
      print('the [{}] is empty or equal None!'.format(strSql))

  def update_Data(self,strSql, data):
    '''更新数据'''
    if strSql is not None and strSql != '':
      if data is not None:
        cursor = self.get_Cursor()
        for d in data:
          if self.print_sql:
            print('执行sql:[{}],参数:[{}]'.format(strSql, d))
          cursor.execute(strSql, d)
          self.commit()
        self.close_Cursor(cursor)
    else:
      rint('the [{}] is empty or equal None!'.format(strSql))

  def delete_multiData(self,strSql, data):
    '''删除多条sql数据'''
    if strSql is not None and strSql != '':
      if data is not None:
        cursor = self.get_Cursor()
        for d in data:
          if self.print_sql:
            print('执行sql:[{}],参数:[{}]'.format(strSql, d))
          cursor.execute(strSql, d)
          self.commit()
        self.close_Cursor(cursor)
    else:
      rint('the [{}] is empty or equal None!'.format(strSql))

  def delete_Data(self,strSql):
    '''删除一条sql数据'''
    if strSql is not None and strSql != '':
      if self.print_sql:
        print('执行sql:[{}]'.format(strSql))
        cursor = self.get_Cursor()
        cursor.execute(strSql)
        self.commit()
        self.close_Cursor(cursor)
    else:
      print('the [{}] is empty or equal None!'.format(strSql))

#########################################################################
#测试代码
#########################################################################



db = MySqlDB()

#删除数据表
#db.drop_Table('person')
#ENGINE=InnoDB DEFAULT CHARSET=utf8

#创建数据库表
create_table_sql = '''CREATE TABLE `person` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`gender` varchar(4) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
);'''

#db.create_Table(create_table_sql)

#删除数据、
delSql='delete from person '
#db.delete_Data(delSql)

#插入数据测试,插入一条语句
insert_sql ='''INSERT INTO person VALUES (3, 'xiaoli', '女', 18, '山东')'''
#db.insert_Data(insert_sql)

#插入数据测试,插入多条语句


insert_sql = '''INSERT INTO person values (%s, %s, %s, %s, %s)'''


data = [[1, 'xiaowang', '男', 20, '广东'],
[2, 'xiaozhang', '男', 22, '河南'],
[3, 'xiaoli', '男', 18, '山东'],
[4, 'xiaoliu', '女', 21, '山西']]


db.insert_MultiData(insert_sql,data)

#查询数据
a= db.get_All_Item('select * from person')

for item in a:
for it in item:
print it

posted on 2016-07-05 11:07  shaomine  阅读(519)  评论(0编辑  收藏  举报