1. pymysql的基本使用mysql
# -*- coding:utf-8 -*- # Author:Wong Du import pymysql # 建立連接,至關於創建一個socket conn = pymysql.Connection(host='10.0.0.100', port=3306, user='root', passwd='123456', db='testdb') # 創建遊標,至關於進入 mysql> 命令操做界面 cursor = conn.cursor() # 建表,和mysql命令行操做同樣 try: create_table = cursor.execute('''create table student( id int not null primary key auto_increment, name char(32) not null, register_date date not null DEFAULT "2018-05-09" ); ''') except pymysql.err.InternalError as e: # print(type(e)) print("\033[31;1m%s; Do nothing...\033[0m" %e) # 插入數據 insert = cursor.execute('insert into student (name,register_date) values("junry", "2017-03-14");') insert2 = cursor.execute('insert into student (name,register_date) values("hongfa", "2015-03-14");') insert3 = cursor.execute('insert into student (name,register_date) values("jinglin", "2016-03-14");') # 查看錶數據 select = cursor.execute('select * from student;') for line in cursor.fetchall(): print(line) # 修改表數據 update = cursor.execute('update student set name="junwei" where id=1') select2 = cursor.execute('select * from student;') print(cursor.fetchone()) # 刪除表數據 delete = cursor.execute('delete from student;') select3 = cursor.execute('select * from student;') if cursor.fetchall(): print(cursor.fetchall()) else: print("This is a empty table...") # 提交 conn.commit() cursor.close() # 關閉遊標 conn.close() # 關閉鏈接 # 等等 等等。。。
循環插入數據sql
# -*- coding:utf-8 -*- # Author:Wong Du import pymysql # 創建鏈接 conn = pymysql.Connect(host='10.0.0.100', port=3306, user='root', passwd='123456', db='testdb') # 建立遊標 cursor = conn.cursor() # 循環插入列表 many_list = [ ('zhangsan', '2011-11-11'), ('lisi', '2012-11-11'), ('wangwu', '2022-10-09'), ] # 循環插入(插入多條內容) cursor.executemany("insert into student (name, register_date) VALUE(%s, %s);", many_list) # 修改遊標位置 cursor.scroll(1, mode='relative') # 相對移動,默認爲relative cursor.scroll(1, mode='absolute') # 絕對移動 # fetchone()獲取一行數據、fetchmany(num)獲取指定行數據、fetchall()獲取全部行數據 cursor.execute("select * from student;") for line in cursor.fetchall(): print(line) # 清楚student表的數據 cursor.execute("delete from student;") # 提交 conn.commit() cursor.close() # 關閉遊標 conn.close() # 關閉鏈接