shi-qi

python 连接mysql :

  1),连接数据库,必须关闭连接,关闭游标对象。
  2),fetchall() 返回所有的对象,数据类型为元组!
  3),通过游标对象来操作 sql语句,以及返回得到的数据! 
  4),游标对象是一个迭代器,因此会按照上次所在的位置,继续取数据。
from pymysql import *
def main():
    conn = connect(host=\'localhost\', port=3306, user="root", password="x", database="jing_dong", charset=\'utf8\')
    # 得到游标对象
    cs1 = conn.cursor()
    # sql语句
    sql = """ select * from goods """

    # 2执行Sql语句
    cs1.execute(sql)

    print(cs1.fetchone())  # 迭代查询 由于15行已经迭代完毕了,因此不在查到数据
    print(cs1.fetchmany(3))
    # 获取这个数据
    table_data = cs1.fetchall()
    print(\'\n\')

    # print(cs1.fetchone())  # 迭代查询 由于15行已经迭代完毕了,因此不在查到数据
    # print(cs1.fetchmany(3))  # 按照上一次的再次迭代三个
    # 关闭
    cs1.close()
    conn.close()
    for i in table_data:
        print(i)

if __name__ == \'__main__\':
    main()

2, 连接数据库相当于开启了事务,如果是修改数据库数据,那么就必须实行关闭事务操作。

conn = connect(host=\'localhost\', port=3306, user="root", password="x", database="jing_dong", charset=\'utf8\')
conn.commit()

 

分类:

技术点:

相关文章:

  • 2021-08-31
  • 2021-12-08
  • 2021-11-28
  • 2022-01-11
  • 2021-07-22
  • 2022-01-07
  • 2021-08-10
猜你喜欢
  • 2021-10-24
  • 2021-11-21
  • 2021-11-28
  • 2021-11-28
  • 2021-11-28
  • 2021-07-27
  • 2021-11-04
相关资源
相似解决方案