python3 之pymysql 連接mysql數據庫

pymsqlPython中操作MySQL的模塊並且只有在Python3.0版本中才存在,其使用方法和MySQLdb幾乎相同

下載安裝pymsql模塊

pip3 install pymysql

操作前準備

#1.創建數據庫
mysql> create database mydb;
mysql> use mydb;

#2.創建表
create table students
    (
        id int  not null auto_increment primary key,
        name char(8) not null,
        sex char(4) not null,
        age tinyint unsigned not null,
        tel char(13) null default "-"
    );

#3.插入兩條數據
mysql> insert  into students values(1,"jack","M",20,"stu");
mysql> insert  into students values(2,"xander","M",20,"stu");

1.執行SQL

import pymysql

# 創建mysql連接(socket),client --> server
"""
host = "Server端IP"
port = "Server端口"
user = "Server端用戶"
passwd = "Server端密碼"
db = "Server端數據庫名"
"""
conn = pymysql.connect(host="10.0.0.51",port=3306,user="root",passwd="123456",db="mydb")

#創建遊標(光標位置),相當於是socket上的實例
cursor = conn.cursor()

# 執行SQL語句,並返回受影響的行數
"""
cursor.execute("需要執行的sql語句")
"""
effect_row = cursor.execute("select * from students")
print(cursor.fetchone())    # 獲取第一條數據
print(cursor.fetchone())    # 獲取第二條數據
print("------")
print(cursor.fetchall())    # 獲取所有數據(從未被獲取的數據中讀出來)

# 提交SQL語句執行結果,不然無法保存新建或者修改的數據
conn.commit()

# 關閉遊標
cursor.close()

# 關閉MySQL連接
conn.close()

2.插入數據

import pymysql

# 創建mysql連接(socket),client --> server
conn = pymysql.connect(host="10.0.0.51",port=3306,user="root",passwd="123456",db="mydb")

#創建遊標(光標位置),相當於是socket上的實例
cursor = conn.cursor()

# 定義需要插入的數據
data = [
    ("Daniel","M","21","stu"),
    ("Noah","M","25","stu"),
    ("David", "M", "25", "stu")
]

# 執行插入SQL語句
cursor.executemany("insert into students(name,sex,age,tel) values(%s,%s,%s,%s)" ,data)

# 提交SQL語句執行結果,不然無法保存新建或者修改的數據
conn.commit()

# 關閉遊標
cursor.close()

# 關閉MySQL連接
conn.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章