軟硬件環境
OS X EI Capitan
Python 3.5.1
mysql 5.6
前言
在開發中經常涉及到數據庫的使用,而python對于數據庫也有多種解決方法。本文以python3中的mysql為例,介紹pymysql模塊的使用。
準備數據庫
創建一個mysql數據庫,名字叫testdb,建立一張表叫testtable,它有3個字段,分別是id,數據類型是INT(11),設為主鍵、非空、UNSIGNED、AUTO INCREMENT,name,數據類型是VARCHAR(45),設為非空、唯一,sex,數據類型是VARCHAR(45),設為非空
python3 源碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
# -*- coding: utf-8 -*- 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() |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。