python3不支持python2方式链接mysql,但是可以用pymysql驱动包链接操作MySQL数据。
具体步骤如下:
2、解压后进入pymysql根目录,sudo python3 setup.py install ;安装过程没有报错就成功了。pymysql的API使用文档:
以下是对表的crud操作:
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'wolf'
'''created time : 16/11/12'''
import unittest
import pymysql
class CRUDMysql(unittest.TestCase):
__connection = None
def setUp(self):
print("operator before .....")
self.__connection = pymysql.connect(host='localhost', user='root', password='root',db='dev', port=3306, charset='utf8',cursorclass=pymysql.cursors.DictCursor)
def tearDown(self):
print("operator after")
self.__connection.close()
def test_add(self):
try:
with self.__connection.cursor() as cursor:
sql = "INSERT INTO `tb_book` (`name`, `description`) VALUES (%s, %s)"
cursor.execute(sql, ('python', 'wolf first connection mysql by python'))
self.__connection.commit()
except Exception :
self.__connection.rollback()
print('insert exception.....')
raise
def test_qry_one(self):
try:
sql = "SELECT * FROM tb_book WHERE id = %d" % (1)
cursor = self.__connection.cursor()
cursor.execute(sql)
book = cursor.fetchone()
print(book)
except Exception:
print('qryOne exception...')
raise
def test_qry_books(self):
try:
with self.__connection.cursor() as cursor:
sql = "SELECT * FROM tb_book"
cursor.execute(sql)
datas = cursor.fetchall()
for book in datas:
print("id:" + str(book['id']) + ' name: ' + book['name'] + ' desc: ' + book['description'])
except Exception:
print('query exception...')
raise
def test_delete(self):
try:
sql = "DELETE FROM tb_book WHERE id = %d" % (6)
cursor = self.__connection.cursor()
cursor.execute(sql)
self.__connection.commit()
except:
print('delete exception ... ')
self.__connection.rollback()
raise以上属于本人自己的学习笔记,如果读者有不懂的可以留言,但是请勿喷,谢谢