python3操作mysql數(shù)據(jù)庫的方法
軟硬件環(huán)境
OS X EI Capitan
Python 3.5.1
mysql 5.6
前言
在開發(fā)中經(jīng)常涉及到數(shù)據(jù)庫的使用,而python對(duì)于數(shù)據(jù)庫也有多種解決方法。本文以python3中的mysql為例,介紹pymysql模塊的使用。
準(zhǔn)備數(shù)據(jù)庫
創(chuàng)建一個(gè)mysql數(shù)據(jù)庫,名字叫testdb,建立一張表叫testtable,它有3個(gè)字段,分別是id,數(shù)據(jù)類型是INT(11),設(shè)為主鍵、非空、UNSIGNED、AUTO INCREMENT,name,數(shù)據(jù)類型是VARCHAR(45),設(shè)為非空、唯一,sex,數(shù)據(jù)類型是VARCHAR(45),設(shè)為非空
python3 源碼
# -*- coding: utf-8 -*- __author__ = 'djstava@gmail.com' import logging import pymysql class MySQLCommand(object): def __init__(self,host,port,user,passwd,db,table): self.host = host self.port = port self.user = user self.password = passwd self.db = db self.table = table def connectMysql(self): try: self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.password,db=self.db,charset='utf8') self.cursor = self.conn.cursor() except: print('connect mysql error.') def queryMysql(self): sql = "SELECT * FROM " + self.table try: self.cursor.execute(sql) row = self.cursor.fetchone() print(row) except: print(sql + ' execute failed.') def insertMysql(self,id,name,sex): sql = "INSERT INTO " + self.table + " VALUES(" + id + "," + "'" + name + "'," + "'" + sex + "')" try: self.cursor.execute(sql) except: print("insert failed.") def updateMysqlSN(self,name,sex): sql = "UPDATE " + self.table + " SET sex='" + sex + "'" + " WHERE name='" + name + "'" print("update sn:" + sql) try: self.cursor.execute(sql) self.conn.commit() except: self.conn.rollback() def closeMysql(self): self.cursor.close() self.conn.close()
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python3實(shí)現(xiàn)將本地JSON大數(shù)據(jù)文件寫入MySQL數(shù)據(jù)庫的方法
- Python3實(shí)現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作示例
- Python3實(shí)現(xiàn)的Mysql數(shù)據(jù)庫操作封裝類
- python3連接MySQL數(shù)據(jù)庫實(shí)例詳解
- Python3.6簡單操作Mysql數(shù)據(jù)庫
- 在python3環(huán)境下的Django中使用MySQL數(shù)據(jù)庫的實(shí)例
- python3.4用函數(shù)操作mysql5.7數(shù)據(jù)庫
- python3使用PyMysql連接mysql數(shù)據(jù)庫實(shí)例
- linux下python3連接mysql數(shù)據(jù)庫問題
- python3對(duì)接mysql數(shù)據(jù)庫實(shí)例詳解
相關(guān)文章
Python2實(shí)現(xiàn)的LED大數(shù)字顯示效果示例
這篇文章主要介紹了Python2實(shí)現(xiàn)的LED大數(shù)字顯示效果,涉及Python的簡單交互與列表相關(guān)使用技巧,需要的朋友可以參考下2017-09-09python實(shí)現(xiàn)自動(dòng)登錄后臺(tái)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)自動(dòng)登錄后臺(tái)管理系統(tǒng),并進(jìn)行后續(xù)操作,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10Python基于textdistance實(shí)現(xiàn)計(jì)算文本相似度
textdistance是Python的第三方庫,用于計(jì)算文本之間的相似度或距離,本文主要為大家詳細(xì)介紹了如何使用textdistance實(shí)現(xiàn)計(jì)算文本相似度,需要的可以了解下2024-03-03