当前位置:Gxlcms > 数据库问题 > 使用pycharm连接数据库及进行一些简单的操作

使用pycharm连接数据库及进行一些简单的操作

时间:2021-07-01 10:21:17 帮助过:26人阅读

一般的开发过程中,我们需要使用pycharm来连接数据库,从而来进行对数据库的操作,这里主要连接的是mysql数据库,另外加了使用pandas模块读取数据库的操作,基本的操作如下所示:

  • 直接连接数据库
  1. <code>import pymysql
  2. conn = pymysql.connect(host='localhost',port=3306,db='joker',user='root',password='root')
  3. # 定义一个标志位,用于控制要执行那种操作
  4. flag = 3
  5. # 创建一个cursor(游标)对象,用于执行SQL语句
  6. cursor = conn.cursor(pymysql.cursors.DictCursor)
  7. '''
  8. pymysql.cursors.DictCursor的作用:让查询结果以字典的形式展示
  9. 查询结果:{'id': 8, 'name': 'joker', 'age': 24}
  10. '''
  11. # 增
  12. if flag == 0:
  13. # sql = 'insert into student(name,age) values("joker",24)' # 直接将数据填充进去
  14. sql = 'insert into student(name,age) values(%s,%s)' # 使用占位符占位,之后传参
  15. row = cursor.execute(sql,('joker',24)) # 参数为一个(即新添加一行数据记录)时使用
  16. # cursor.executemany(sql,[('tom',38),('jack',26)]) # 参数为多个(即新添加多行数据记录)时使用
  17. print(row)
  18. # 删
  19. if flag == 1:
  20. sql = 'delete from student where name=%s'
  21. row = cursor.execute(sql,('joker',))
  22. print(row)
  23. # 改
  24. if flag == 2:
  25. # sql = 'update student set age=%s'
  26. sql = 'update student set age=%s where name=%s'
  27. row = cursor.execute(sql,(28,'tom'))
  28. print(row)
  29. # 查
  30. if flag == 3:
  31. sql = 'select * from student'
  32. cursor.execute(sql)
  33. print(cursor.fetchall()) # 查看全部
  34. # cursor.scroll(-3,'relative')
  35. '''
  36. scroll:用于控制查询开始的位置,类似于控制指针or索引
  37. relative:相对地址,absolute:绝对地址,2表示在各个地址上的偏移量
  38. '''
  39. cursor.scroll(2,'absolute')
  40. print(cursor.fetchmany(144)) # 查看指定个数,个数(参数)可无限大,取值只会取全部值为止
  41. print(cursor.fetchone()) # 查看一个
  42. conn.commit()
  43. cursor.close()
  44. conn.close()
  45. </code>
  • 使用pandas来读取数据库

    1. <code>import pandas as pd
    2. import pymysql
    3. # 创建连接对象
    4. conn = pymysql.connect(host='localhost',port=3306,user='root',password='cyh4414',db='joker')
    5. # 编写SQL语句
    6. sql = 'select * from student'
    7. # 使用pandas进行查询
    8. data = pd.read_sql(sql=sql,con=conn)
    9. print(data)
    10. </code>

使用pycharm连接数据库及进行一些简单的操作

标签:开发   sql   mit   abs   any   char   tom   python   多行   

人气教程排行