连接mysql
pip install pymysql
import pymysql
conn=pymysql.connect(host='192.168.0.6',port=3306,user='root',password='123456',db='oldboydb')#创建连接
cursor=conn.cursor()#创建游标
#执行并返回受影响的行数
result=cursor.execute('insert into student(name,age,register_date) values ("haha","22","2016-03-02")')
print('受影响的行数:',result)
new_id=cursor.lastrowid#最近的自增id
print("最近的自增id:",new_id)#不提交id也会自增上去
#执行一行
update=cursor.execute("update student set name='Laha' where name='haha' ")
delete=cursor.execute("delete from student where name='Laha'")
#执行多行
result_many=cursor.executemany("insert into B(b) values(%s)",['7','8','9','10','11','12'])
print("result many:",result_many)
#查询
effect_row=cursor.execute('select *from B')
row_1=cursor.fetchone()#获取一行
print("第一行查询结果:",row_1)
row_2=cursor.fetchmany(2)#获取多行
print("第二行第三行结果:",row_2)
row_all=cursor.fetchall()#获取全部
print("剩下的结果:",row_all)
conn.commit()# 递交之后就会写入数据库 不提交就不会 默认事务
cursor.close()#关闭游标
conn.close()#关闭连接
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。