pymysql类库学习记录

举报
建帅小伙儿 发表于 2022/09/25 01:24:12 2022/09/25
【摘要】 一、代码如下 1.创建数据库连接conn = pymysql.connect( user='array', password='admin', host='192.168.120.216', prot=3306, charset='uft8', database='uag') 返回一个数据库连接对象 2.创建游标 cursor...

一、代码如下


   
  1. 1.创建数据库连接
  2. conn = pymysql.connect(
  3. user='array',
  4. password='admin',
  5. host='192.168.120.216',
  6. prot=3306,
  7. charset='uft8',
  8. database='uag'
  9. )
  10. 返回一个数据库连接对象
  11. 2.创建游标
  12. cursor = conn.cursor(cursor=None)
  13. 返回一个游标对象
  14. 3.创建sql语句
  15. sql = "select * from uag;"
  16. 4.执行sql语句,并返回受影响行数
  17. effect_row = cursor.excute(sql)
  18. 5.提交数据,否则无法保存修改的数据
  19. conn.commit()
  20. 6.关闭游标
  21. cursor.close()
  22. 7.断开连接
  23. conn.close()

二.案例代码


   
  1. # coding=utf-8
  2. """
  3. 作者:gaojs
  4. 功能:
  5. 新增功能:
  6. 日期:2022/4/17 13:59
  7. """
  8. import pymysql
  9. class Database:
  10. def __init__(self):
  11. # 连接数据库
  12. self.connect = pymysql.Connect(
  13. host='localhost',
  14. port=3306,
  15. user='root',
  16. passwd='admin',
  17. db='gaojs_test',
  18. charset='UTF8'
  19. )
  20. # 获取游标
  21. self.cursor = self.connect.cursor()
  22. self.cursor.execute("SELECT VERSION()")
  23. # 使用 fetchone() 方法获取单条数据.
  24. data = self.cursor.fetchone()
  25. print("Database version : %s " % data)
  26. def create_table(self):
  27. """
  28. 创建表
  29. :return:
  30. """
  31. # 切换数据库
  32. self.cursor.execute("use gaojs_test;")
  33. # 创建表语句
  34. self.cursor.execute("DROP TABLE IF EXISTS tb_gjs")
  35. self.cursor.execute("DROP TABLE IF EXISTS gaojs")
  36. # 使用预处理语句创建表
  37. sql = "CREATE TABLE tb_gjs( number char(10), name varchar(50), age int, gender varchar(10) , salary char(20));"
  38. sql1 = "CREATE TABLE gaojs(sid char(15), yuwen char(10), shuxue varchar(50), english int, physics varchar(10) , history char(20), computer char(20));"
  39. self.cursor.execute(sql)
  40. self.cursor.execute(sql1)
  41. self.cursor.execute("desc tb_gjs;")
  42. self.connect.commit()
  43. def insert_sql(self):
  44. """
  45. update插入数据: UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
  46. :return:
  47. """
  48. # self.cursor.execute("update tb_gjs set phone='13666666666' where name='qiubing';")
  49. # self.cursor.execute("update tb_gjs set phone='13688888888' where name='gaojianshuai';")
  50. self.cursor.execute("INSERT INTO tb_gjs (number, name, age, gender, salary) VALUE ('001', 'gaojianshuai', 30, 'man', '16000')")
  51. self.cursor.execute("INSERT INTO tb_gjs (number, name, age, gender, salary) VALUE ('002', 'chensishi', 27, 'woman', '18000')")
  52. self.cursor.execute("INSERT INTO tb_gjs (number, name, age, gender, salary) VALUE ('003', 'arraynetworks', 30, 'man', '19000')")
  53. self.connect.commit()
  54. def update(self):
  55. """
  56. 更新数据
  57. :return:
  58. """
  59. self.cursor.execute("update tb_gjs set phone='13666666666' where name='qiubing';")
  60. self.connect.commit()
  61. def disconnect_db(self):
  62. """
  63. 断开数据库
  64. :return:
  65. """
  66. self.connect.commit()
  67. self.connect.close()
  68. def alter_table(self):
  69. """
  70. 新增加列
  71. :return:
  72. """
  73. self.cursor.execute("alter table tb_gjs add column company varchar(20) after salary;")
  74. self.cursor.execute("""insert into tb_gjs (number, name, age, gender, salary, company) values ('006', 'wanghuan', 22, 'nv', '35000', 'Camlot');""")
  75. self.connect.commit()
  76. def delete_procedure(self):
  77. """
  78. 存储过程
  79. :return:
  80. """
  81. self.cursor.execute("""
  82. CREATE PROCEDURE delete_age(IN p_age INTEGER)
  83. BEGIN
  84. DELETE FROM tb_gjs
  85. WHERE age = p_age;
  86. END$$
  87. """)
  88. self.cursor.execute("call delete_age(22);")
  89. test = Database()
  90. test.create_table()
  91. test.insert_sql()
  92. test.alter_table()
  93. test.delete_procedure()

三、案例2


   
  1. import pymysql
  2. from pymysql_test import Database
  3. def get_conn():
  4. # 连接数据库
  5. connect = pymysql.Connect(
  6. host='localhost',
  7. port=3306,
  8. user='root',
  9. passwd='admin',
  10. db='gaojs_test',
  11. charset='UTF8'
  12. )
  13. return connect
  14. # # 获取游标
  15. # cursor = connect.cursor()
  16. # cursor.execute("SELECT VERSION()")
  17. # # 使用 fetchone() 方法获取单条数据.
  18. # data = cursor.fetchone()
  19. # print("Database version : %s " % data)
  20. def load_file_to_mysql():
  21. conn = get_conn()
  22. try:
  23. with open('student.txt', encoding='utf-8') as f:
  24. for line in f:
  25. line = line.strip()
  26. sid, chinese, math, english, phisics, history, computer = line.split("\t")
  27. sql = f"insert into gaojs (sid, chinese, math, english, phisics, history, computer) values ({sid}, {chinese}, {math}, {english}, {phisics}, {history}, {computer})"
  28. cursor = conn.cursor()
  29. cursor.execute(sql)
  30. cursor.commit()
  31. finally:
  32. if conn is not None:
  33. conn.close()
  34. if __name__ == '__main__':
  35. load_file_to_mysql()

文章来源: blog.csdn.net,作者:懿曲折扇情,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/qq_41332844/article/details/126837322

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。