1. 程式人生 > >Python中pymysql基本使用

Python中pymysql基本使用

ngs any 一行 。。 span 關閉 student incr execute

Python中pymysql模塊通過獲取mysql數據庫命令行遊標執行數據庫命令來進行數據庫操作

  優點:操作數據庫語句所見即所得,執行了什麽數據庫語句都很清楚

  缺點:操作繁瑣,代碼量多

1. pymysql的基本使用

# -*- 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() # 關閉連接 # 等等 等等。。。

循環插入數據

# -*- 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()    # 關閉連接

Python中pymysql基本使用