mysql与python的交互
Posted 花有重开日,人无再少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql与python的交互相关的知识,希望对你有一定的参考价值。
##导包 import pymysql #封装方法 def main(): #创建mysql连接 conn = pymysql.connect(host=‘localhost‘,port=3306,database=‘python01‘,user=‘root‘,password=‘858362‘,charset=‘utf8‘) #创建cursor,接受mysql语句并且执行的对象方法 cursor = conn.cursor() #插入10万数据 for x in range(100000): cursor.execute("insert into test_index values(‘ha - %s‘,‘ca - %s‘)"%(x,x)) conn.commit() if __name__ == ‘__main__‘: main()
import pymysql def test(): conn=pymysql.connect(host=‘localhost‘,port=3306,database=‘message‘,user=‘root‘,password=‘858362‘,charset=‘utf8‘) cursor=conn.cursor() cursor.execute(‘select * from classify‘) ret=cursor.fetchall() print(ret) cursor.execute(‘select * from news where id = 1‘) r=cursor.fetchone() print(r) cursor.execute(‘delete from news where id = 2‘) cursor.execute(‘select * from news‘) e=cursor.fetchall() print(e) cursor.execute(‘update news set name = "张三" where id = 3‘) cursor.execute(‘select * from news where id = 3‘) a=cursor.fetchone() print(a) cursor.execute(‘select * from news where s_news = 1‘) vv=cursor.fetchall() print(vv) cursor.execute(‘select * from news where (count>5 and is_delete = "是")‘) ew=cursor.fetchone() print(ew) conn.commit() cursor.close() conn.close() if __name__ == ‘__main__‘: test()
import pymysql # # #创建函数 def main(): #建立mysql连接 conn = pymysql.connect(host=‘127.0.0.1‘,port=3306,user=‘root‘,password=‘858362‘,database=‘python01‘,charset=‘utf8‘) #创建cursor对象,执行sql语句,声明游标对象返回dict cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select * from students")#select * from students ret=cursor.fetchone() # ret=cursor.fetchall() # print(ret) # print(ret[4]) # print(ret[4][‘name‘]) print(ret[‘name‘]) cursor.close() conn.close() if __name__ == ‘__main__‘: main()
以上是关于mysql与python的交互的主要内容,如果未能解决你的问题,请参考以下文章