python mysql curd_python3对MySQL的CRUD

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以上属于本人自己的学习笔记,如果读者有不懂的可以留言,但是请勿喷,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值