1.建库

  1. import pymysql
  2. # 建库
  3. try:
  4. conn=pymysql.connect(
  5. host='127.0.0.1',
  6. port=3306,
  7. user='root',
  8. passwd='',
  9. )
  10. cur=conn.cursor()
  11. create_database_sql='CREATE DATABASE IF NOT EXISTS py3_tstgr DEFAULT CHARSET utf8 COLLATE utf8_general_ci;'
  12. cur.execute(create_database_sql)
  13. cur.close()
  14. print('创建数据库 py3_tstgr 成功!')
  15. except pymysql.Error as e:
  16. print('pymysql.Error: ',e.args[0],e.args[1])

2.建表

  1. import pymysql
  2. # 建表
  3. try:
  4. conn=pymysql.connect(
  5. host='127.0.0.1',
  6. port=3306,
  7. user='root',
  8. passwd='',
  9. db='py3_tstgr',
  10. charset='utf8'
  11. )
  12. cur=conn.cursor()
  13. cur.execute('drop table if exists user;')
  14. create_table_sql='''
  15. CREATE TABLE user(
  16. id int(11) DEFAULT NULL ,
  17. name VARCHAR(50) DEFAULT NULL ,
  18. password VARCHAR(30) DEFAULT NULL ,
  19. birthday TIMESTAMP DEFAULT now()
  20. )engine=innodb DEFAULT CHARACTER set utf8;
  21. '''
  22. cur.execute(create_table_sql)
  23. print('创建数据库表成功!')
  24. except pymysql.Error as e:
  25. print('mysql.Error: ',e.args[0],e.args[1])

3.增、改、删、查数据操作

  1. import pymysql
  2. # 数据库操作
  3. # 连接
  4. def db_conn(host,port,user,passwd,db_name):
  5. try:
  6. conn=pymysql.connect(
  7. host=host,
  8. port=port,
  9. user=user',
  10. passwd=password,
  11. db=db_name,
  12. charset='utf8',
  13. )
  14. # cur=conn.cursor()
  15. print('数据库连接成功!')
  16. # 返回连接
  17. return conn
  18. except pymysql.Error as e:
  19. print('数据库连接失败')
  20. print('mysql.Error: ',e.args[0],e.args[1])
  21.  
  22. def db_cur(conn):
  23. # 获取游标
  24. cur=conn.cursor()
  25. return cur
  26.  
  27. def db_close(cur,conn):
  28. # 游标关闭
  29. cur.close()
  30. # 提交事务
  31. conn.commit()
  32. # 连接关闭
  33. conn.close()
  34.  
  35. # 插入单行数据
  36. def db_insert_data(sql,cur,*args):
  37. try:
  38. # print(args)
  39. result=cur.execute(sql,args)
  40. print('添加语句受影响的行数:',result)
  41. except Exception as e:
  42. print('db_insert_data error: ',e.args)
  43.  
  44. # 批量插入数据
  45. def db_insert_datas(sql,cur,list_datas):
  46. try:
  47. result=cur.executemany(sql,list_datas)
  48. print('批量插入受影响的行数:',result)
  49. except Exception as e:
  50. print('db_insert_datas error: ',e.args)
  51.  
  52. # 修改单行数据
  53. def db_update(sql,cur):
  54. result=cur.execute(sql)
  55. print('修改语句受影响的行数:',result)
  56.  
  57. # 批量修改数据
  58. def db_update_datas(sql,cur,list_datas):
  59. try:
  60. result=cur.executemany(sql,list_datas)
  61. print('批量修改受影响的行数:',result)
  62. except Exception as e:
  63. print('db_update_datas error: ',e.args)
  64.  
  65. # 删除单行数据
  66. def db_delete_data(sql,cur):
  67. result=cur.execute(sql)
  68. print('删除语句受影响的行数:',result)
  69.  
  70. # 批量删除数据
  71. def db_delete_datas(sql,cur,list_datas):
  72. try:
  73. result=cur.executemany(sql,list_datas)
  74. print('批量删除受影响的行数:',result)
  75. except Exception as e:
  76. print('db_delete_datas error: ',e.args)
  77.  
  78. # 回滚
  79. def roll_back(conn):
  80. try:
  81. conn.rollback()
  82. print('回滚完成!')
  83. except Exception as e:
  84. print('rollback error: ',e.args)
  85.  
  86. def db_select_data(sql,cur):
  87. result=cur.execute(sql)
  88. print('查询语句受影响的行数:',result)
  89.  
  90. def db_select_datas(sql,cur,list_datas):
  91. try:
  92. result=cur.executemany(sql,list_datas)
  93. print('批量查询受影响的行数:',result)
  94. except Exception as e:
  95. print('db_select_datas error: ',e.args)
  96.  
  97. if __name__=="__main__":
  98.  
  99. host='127.0.0.1'
  100. port=3306
  101. user='root'
  102. passwd=''
  103. db='py3_tstgr'
  104. conn=db_conn(host,port,user,passwd,db)
  105. print(conn)
  106. cur=db_cur(conn)
  107. print(cur)
  108.  
  109. insert_sql="insert into user values(1,'tom','123','1990-01-01');"
  110. db_insert_data(insert_sql,cur)
  111.  
  112. insert_sql2="insert into user values(%s,%s,%s,%s);"
  113. db_insert_data(insert_sql2,cur,2,'lucy','aaa','1991-02-02')
  114.  
  115. insert_datas_sql="insert into user values(%s,%s,%s,%s);"
  116. list_datas=[(2,'ha2','','1992-02-02'),(3,'ha3','','1993-03-03'),(4,'ha4','','1994-04-04')]
  117. db_insert_datas(insert_datas_sql,cur,list_datas)
  118.  
  119. # 查询数据
  120. sql="select * from user;"
  121. cur.execute(sql)
  122. res1=cur.fetchone() # 获取一行数据
  123. print(res1)
  124. res2=cur.fetchmany(2) #获取多行数据
  125. print(res2)
  126. res3=cur.fetchall() # 获取所有数据
  127. print(res3)
  128. print(cur.fetchone()) # None
  129. # 重置游标
  130. cur.scroll(1,mode='relative')
  131. print(cur.fetchone())
  132.  
  133. # 更新数据
  134. up_sql="update user set name='lala' where password='123';"
  135. db_update(up_sql,cur)
  136.  
  137. # 批量更新数据
  138. up_sqls="update user set name=%s where password=%s;"
  139. up_datas=[('lw',''),('lc','aaa')]
  140. db_update_datas(up_sqls,cur,up_datas)
  141.  
  142. # 删除数据
  143. delete_sql="delete from user where name='lw';"
  144. db_delete_data(delete_sql,cur)
  145.  
  146. delete_sqls="delete from user where name=%s;"
  147. db_delete_datas(delete_sqls,cur,[('lc'),('hah2'),('hah3')])
  148.  
  149. # print(cur.rownumber) # 0 获取所在行号
  150.  
  151. # cur.scroll(0,mode='absolute')
  152. # cur.execute('select * from user;')
  153.  
  154. select_sql="select * from user;"
  155. db_select_data(select_sql,cur)
  156. print(cur.fetchall())
  157.  
  158. # roll_back(conn) # 回滚
  159. # print(cur.rownumber)
  160. # cur.scroll(0, mode='absolute')
  161. # cur.execute('select * from user;')
  162.  
  163. # 查询单行
  164. select_sql = "select * from user;"
  165. db_select_data(select_sql, cur)
  166.  
  167. # 批量查询
  168. select_sqls="select * from user where name=%s;"
  169. db_select_datas(select_sqls,cur,[('ha1'),('ha2'),('ha3')])
  170. print(cur.fetchall())
  171.  
  172. db_close(cur,conn) # 断开连接

pymysql操作mysql数据库的更多相关文章

  1. flask + pymysql操作Mysql数据库

    安装flask-sqlalchemy.pymysql模块 pip install flask-sqlalchemy pymysql ### Flask-SQLAlchemy的介绍 1. ORM:Obj ...

  2. 用pymysql操作MySQL数据库

    工具库安装 pip install pymysql 连接关闭数据库与增删改查操作 # 导入pymysql库 import pymysql # 打开数据库连接 # 参数1:数据库服务器所在的主机+端口号 ...

  3. python使用pymysql操作mysql数据库

    1.安装pymysql pip install pymysql 2.数据库查询示例 import pymysql # 连接database conn =pymysql.connect(user=' , ...

  4. PyMySQL操作mysql数据库(py3必学)

    一,安装PyMySQL Python是编程语言,MySQL是数据库,它们是两种不同的技术:要想使Python操作MySQL数据库需要使用驱动.这里选用PyMySQL驱动. 安装方式还是使用pip命令. ...

  5. python 3.6 +pyMysql 操作mysql数据库

    版本信息:python:3.6 mysql:5.7 pyMysql:0.7.11 ########################################################### ...

  6. 使用pymysql 操作MySQL数据库

    安装 pip install pymysql 注:连接前要有可使用的账户及有权限.可操作的数据库 先来一个栗子: import pymysql # 连接database conn = pymysql. ...

  7. 使用pymysql操作mysql数据库

    PyMySQL的安装和连接 PyMySQL的安装 python3. -m pip install pymysql python连接数据库 import pymysql # 创建连接 conn = py ...

  8. pymysql操作mysql

    一.使用PyMySQL操作mysql数据库 适用环境 python版本 >=2.6或3.3 mysql版本>=4.1 安装 可以使用pip安装也可以手动下载安装.使用pip安装,在命令行执 ...

  9. python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy

    内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...

随机推荐

  1. Spring cloud微服务安全实战-3-7API安全机制之数据加密

    这一节来聊一下密码的加密. 加密盐,为了避免两个相同的面加密出来的密文是一样的,每个人的盐不一样, 首先引入工具包,lambdaworks <!-- https://mvnrepository. ...

  2. 基于Python的WEB接口开发与自动化测试 pdf(内含书签)

    基于Python的WEB接口开发与自动化测试 目录 目 录O V目 录章 Python 学习必知 ................................................... ...

  3. F110增强

    1.F110 删除操作的增强: 方法:SE19   ZE_F110_DELETE_CHECK 代码: ENHANCEMENT 1  ZE_F110_DELETE_CHECK.    "act ...

  4. window.open post传参

    目录 前言 获取当前用户信息 使用window.open的两种方式 Get方式 Post方式 前言 我使用的场景是,点击弹窗,然后把我当前用户的消息传过去 获取当前用户信息 打开Chrome浏览器,在 ...

  5. Java连接MongoDB示例

    示例代码: package com.zifeiy.snowflake.handle.etl.mongodb; import java.util.ArrayList; import java.util. ...

  6. 【Leetcode_easy】868. Binary Gap

    problem 868. Binary Gap solution1: class Solution { public: int binaryGap(int N) { ; vector<int&g ...

  7. CSS3 mask 遮罩蒙版效果

    mask demo效果演示:http://dtdxrk.github.io/game/css3-demo/mask.html mask 的属性: -webkit-mask-image:url | gr ...

  8. git的使用学习(一)git的简介和安装

    Git简介 Git是什么? Git是目前世界上最先进的分布式版本控制系统(没有之一). Git有什么特点?简单来说就是:高端大气上档次! 那什么是版本控制系统? 如果你用Microsoft Word写 ...

  9. sublime text3 修改快捷键为eclipse

    Preferences -> Key bindings - User [ { "keys": ["shift+enter"], "command ...

  10. activeMq学习应用

    一.下载 ActiveMQ 5.15.0下载地址 二.安装 解压apache-activemq-5.15.0-bin.zip D:\apache-activemq-5.15.7-bin\apache- ...