mysql 和 python的交互需要用到 pymysql 模块。
安装pymysql:
可以在pycharm上直接安装,也可以使用pip安装:
pip install pymysql
代码饭粒1:查询数据
import pymysql # 创建连接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='111111', db='t1') # 创建游标(建立实例),相当于进入数据库后的光标 cursor = conn.cursor() # 执行SQL,并返回受影响行数 effect_row = cursor.execute("select * from test") print(effect_row) # 返回数据条数 print(cursor.fetchone()) # 取出一条数据 # cursor.scroll(1,mode='relative') # 相对当前位置往下移动1行 print(cursor.fetchmany(2)) # 取出多条数据 # cursor.scroll(2,mode='absolute') # 相对绝对(从头开始)位置移动2行 print(cursor.fetchall()) # 取出所有数据。 # 注意这里取数据是类似文件读取的机制,即取了一行指针就指向下一行,下一次从后面开始取。在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置(上面注释部分),相当于读取文件的seek() data = [ ('ff', 'z'), ('mary', 'DB'), ('rain', 'smith'), ] # 执行SQL,并返回受影响行数 effect_row = cursor.executemany("INSERT INTO test(first_name, last_name) VALUES(%s, %s)", data) print(effect_row) # 获取最新自增ID,也即新数据从这里开始编号 new_id = cursor.lastrowid print(new_id) # 提交,不然无法保存新建或者修改的数据 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close()
输出:
('A', 'B', 1)
('C', 'D', 2)
(('Harry', 'Koter', 3), ('Perter', 'Smith', 4))
(('FF', None, 5), ('AS', 'DF', 6), ('AA', 'BB', 7), ('AS', 'DF', 8))
3
46
继续查询可以看到新插入的数据。
注意:若这里报没有权限,则需要在数据库中进行授权:
grant all on *.* to 'root'@'%' identified by '111111'; flush privileges;
posted on
浙公网安备 33010602011771号