python3 操作mysql数据库

着急下班,直接上代码,有时间回来补充说明:

pymysql 为第三方包,使用前需要自行安装,我直接联网安装的,当然,也可以使用源码安装,根据个人情况而定。

pymysql 主要步骤为:1. 得到链接,拿到游标(通过链接,得到cursor()),

2. 通过cursor,调用execute方法执行sql语句,

3. 若查询数,则通过fetchall()(得到所有数据),fetchone()(得到1条数据)fetchmany()(得到指定条数,数据),

4. 其他的就是有关关闭游标,关闭数据库链接,提交数据,回滚数据,方法如下:

cursor.close()(关闭游标),conn.close()(关闭书库链接),conn.commit()(提交更改,删除和更新数据时候用到),conn.rollbak()(回滚数据,删除和更新时候用到。)

pip install pymysql 安装pymysql模块

代码如下:

  1 # -*- coding: utf-8 -*-
  2 """
  3 Created on Tue Dec 18 09:26:52 2018
  4 
  5 @author: 
  6 """
  7 
  8 import pymysql
  9 
 10 #得到数据库链接
 11 def getConnMySQL(host,port,user,password,db,charset):
 12     global MysqlConn
 13     try:
 14         MysqlConn = pymysql.connect(host = host,
 15                                     port = int(port),
 16                                     user = user,
 17                                     password = password,
 18                                     db = db,
 19                                     charset = charset)
 20     except:
 21         print('connect database failed')
 22         exit(1)
 23         
 24 #创建表
 25 def createTable():
 26     try:
 27         with MysqlConn.cursor() as cursor:
 28             dropsql = '''drop table if exists student;'''
 29             cursor.execute(dropsql)
 30             createsql = '''
 31                          create table student
 32                              (id VARCHAR(20) COMMENT 'id',
 33                               sname VARCHAR(20) COMMENT '姓名',
 34                               sex VARCHAR(2) comment '性别',
 35                               age VARCHAR(20) comment '年龄'
 36                              )
 37                          ENGINE=INNODB DEFAULT CHARSET = utf8;
 38                    '''
 39             b = cursor.execute(createsql)
 40             print(b)
 41             
 42     except Exception as e:
 43         print(e)
 44     finally:
 45         cursor.close()
 46         
 47 #插入数据
 48 def insertData():
 49     ids = '3'
 50     sname = '韩红'
 51     sex = ''
 52     age = '26'
 53 
 54     try:
 55         with MysqlConn.cursor() as cursor:
 56             #定义插入语句
 57             insertsql = """insert into student(id,sname,sex,age)
 58                            values('%s','%s','%s','%s') """% \
 59                            (ids,sname,sex,age)
 60             #执行插入语句
 61             cursor.execute(insertsql)
 62             #数据库提交
 63             MysqlConn.commit()
 64     except Exception as e:
 65         MysqlConn.rollback()
 66         print(e)
 67     finally:
 68         cursor.close()
 69 
 70 #删除数据
 71 def deleteData():
 72     try:
 73         with MysqlConn.cursor() as cursor:
 74             delsql = "delete from student where id = %s"%(3)
 75             #执行sql
 76             cursor.execute(delsql)
 77             #提交
 78             MysqlConn.commit()
 79     except Exception as e:
 80         print(e)
 81         #失败回滚
 82         MysqlConn.rollback()
 83     finally:
 84         cursor.close()
 85 
 86 #更新数据
 87 def upadteData():
 88     try:
 89         with MysqlConn.cursor() as cursor:
 90             updatesql = "update student set id = '%s' where id = '%s' \
 91             and age = '%s'"% (4,3,26)
 92             #执行sql
 93             cursor.execute(updatesql)
 94             #提交
 95             MysqlConn.commit()
 96     except Exception as e:
 97         print(e)
 98         #失败则回滚
 99         MysqlConn.rollback()
100     finally:
101         cursor.close()
102             
103 #fetchone通过查询,得到一条数据
104 def queryDataOne():
105     try:
106         with MysqlConn.cursor() as cursor:
107             #定义查询sql
108             querysql = 'select id,sname,sex,age from student;'
109             #执行sql
110             count = cursor.execute(querysql)
111             #简单逻辑,若有需要则在逻辑内加内容
112             if count <=0:
113                 print("not data")
114             elif count > 0:
115                 #得到一条数据
116                 result = cursor.fetchone()
117                 #此处返回值为一个元组,要得到具体的值,转为列表,根据索引取值
118                 print(type(result))
119                 reslist = list(result)
120                 ids = reslist[0]
121                 sname = reslist[1]
122                 sex = reslist[2]
123                 age = reslist[3]
124                 print(ids,sname,sex,age)
125             else:
126                 pass
127     except Exception as e:
128         print(e)
129     finally:
130         cursor.close()
131         
132 #得到所查询出来的全部数据        
133 def queryDataAll():
134     try:
135         with MysqlConn.cursor() as cursor:
136             querysql = 'select id,sname,sex,age from student;'
137             sqlQuerycnt = cursor.execute(querysql)
138             if sqlQuerycnt <= 0:
139                 print('table is empty')
140             elif sqlQuerycnt > 0:
141                 res = cursor.fetchall()
142                 print(type(res))
143                 for rows in list(res):
144                     print('ids = ' +  rows[0])
145             else:
146                 pass
147     except Exception as e:
148         print(e)
149     finally:
150         cursor.close()
151 
152 #获取前N行数据,若库中没有那么多数据,则有多少取多少。
153 def queryDataMany():
154     try:
155         with MysqlConn.cursor() as cursor:
156             quersql = 'select id,sname,sex,age from student;'
157             querCnt = cursor.execute(quersql)
158             if querCnt <= 0 :
159                 print('table is empty')
160             elif querCnt > 0:
161                 res = cursor.fetchmany(10)
162 #                返回元组(多行情况下,为双重元组,也就是嵌套关系)
163 #                根据需求,来指定具体取几条,然后再确定逻辑
164                 print(type(res))
165                 print(res)
166             else:
167                 pass
168     except Exception as e:
169         print(e)
170     finally:
171         cursor.close()
172 
173 if __name__ == '__main__':
174     
175     #此处可以写个配置文件,通过读取配置文件的方式来得到这些参数,不宜写死。
176     host = '192.168.2.2'
177     port = '3306'
178     user = 'root'
179     password = '123456'
180     db = 'mysql'
181     charset = 'utf8'
182     #链接数据库
183     getConnMySQL(host,port,user,password,db,charset)
184     #创建表
185     createTable()
186     #插入数据
187     insertData()
188     #删除数据
189     deleteData()
190     #更新数据
191     upadteData()
192     #查询一条数据
193     queryDataOne()
194     #查询全部数据
195     queryDataAll()
196     #得到指定条数数据
197     queryDataMany()
198     #关闭数据库链接
199     MysqlConn.close()
200     

猜你喜欢

转载自www.cnblogs.com/blankdog/p/10139783.html