您的位置:首頁>正文

python3對mysql的基本操作,增刪改查

python3對mysql的基本操作, 增刪改查

作者:韭菜學院(youxuancaijing)

1. Mysql的增刪改查的操作的常見命令

顯示當前資料庫伺服器中的資料庫清單:

mysql> SHOW DATABASES;

顯示當前資料庫的資料表:

mysql> SHOW Tables;

顯示表結構:

mysql> describe 表名稱;

創建資料庫:

CREATE DATABASE 資料庫名;

例如: create database mydb;

刪除資料庫:

mysql> DROP DATABASE 庫名;

創建資料表 :

mysql> USE 庫名;

mysql> CREATE TABLE 表名 (欄位名 VARCHAR(20), 欄位名 CHAR(1));

例如:

create table user(

id int(5) NOT NULL auto_increment,

name varchar(20),

passwd varchar(20));

刪除資料表:

mysql> DROP TABLE 表名;

往表中插入記錄:

mysql> INSERT INTO 表名 VALUES ("jack","123456");

更新表中資料:

mysql-> UPDATE 表名 SET 欄位名1='a',欄位名2='b' WHERE 欄位名3='c';

將表中記錄清空:

mysql> DELETE FROM 表名 WHERE 欄位名3='c';

查詢資料:

mysql> SELECT 欄位名1,欄位名2 FROM 表名 WHERE 欄位名3='c';

2. 用Python對Mysql的增刪改查

安裝pymysql模組:pip install PyMySQL

import pymysql

# 創建連接

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='mydb')

# 創建游標

cursor = conn.cursor()

# 修改----執行SQL, 並返回受影響行數

# effect_row = cursor.execute("update user set name=%s,pwd=%s where id=%s", ('aaa','bb', 1))

# 添加----執行SQL, 並返回受影響行數

# cursor.execute("insert into user (name, pwd) values (%s,%s)", ("lidao","aaa"))

# 查詢----

cursor.execute("select * from user")

stus = cursor.fetchall()

for stu in stus:

print("id:%d; name: %s; pwd: %s; " %(stu[0], stu[1], stu[2]))

# 刪除---執行SQL, 並返回受影響行數

cursor.execute("delete from user where id=%s", (2))

# 提交, 不然無法保存新建或者修改的資料

conn.commit()

# 關閉游標

cursor.close()

# 關閉連接

conn.close()

你也可以用帶介面的工具進行增刪改查。

實際專案中, 可以對相關函數做封裝。

同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示