Python簡單操作MySQL命令安裝

2021-08-28 12:20:38 字數 1448 閱讀 1489

安裝平台:windows、py3.x

pymysql是python中操作mysql的模組

#執行pip3 install pymysql命令安裝

mysql版本:mysql-installer-community-8.0.12.0

基本命令

建立資料庫 create database student;

使用資料庫 use student;

顯示所有表 show tables;

import pymysql

#1、建立資料庫連線物件

connect = pymysql.connect(

# host:表示主機位址

# 127.0.0.1 本機ip

# 172.16.21.41 區域網ip

# localhost (local:本地 host:主機 合在一起為本地主機的意思)

# host表示mysql安裝的位址

host=「127.0.0.1」,

user=「root」,

passwd=「123456」,

# mysql預設的埠號是3306

port=3306,

# 資料庫名稱

db=「student」

)#2、建立游標,用於操作表

cursor = connect.cursor()

3、建立表

create_table = 「create table if not exists stu (name varchar(30), age integer, phone varchar(11))」

cursor.execute(create_table)

#4、表的增、刪、改、查

#增加insert_table = 「insert into stu (name,age,phone) values (『張三』, 19, 『13332001256』)」

cursor.execute(insert_table)

刪除delete_table = 「delete from stu where name=『張三』」

cursor.execute(delete_table)

修改update_table = 「update stu set age = 20 where id < 10」

cursor.execute(update_table)

查詢select_table = 「select * from stu」

res = cursor.execute(select_table)

s = res.fetchone()

print(s)

ss = res.fetchall()

print(ss)

5、提交sql語句

connect.commit()

6、關閉游標、資料庫

cursor.close()

connect.close()

通過python簡單操作MySQL

pip install pymysql開始操作前需要匯入乙個包 import mysqldb用mysqldb中的connect 函式連線對應的資料庫 連線資料庫 conn mysqldb.connect host localhost mysql的ip port 3306,預設埠3306 user r...

用Python對MySQL簡單操作

import pymysql 連線資料庫 conn pymysql.connect host localhost user root password helloguitar532123 charset utf8 獲得浮標 cursor conn.cursor 建立資料庫 sql create cr...

Mysql簡單操作

建立資料庫 create database 資料庫名稱 資料庫使用 use 資料庫名稱 建立資料表的格式 create table 表明 列名1 資料型別 約束,列名2 資料型別 約束,列名3 資料型別 約束,列名4 資料型別 約束,列名5 資料型別 約束 建立使用者表,使用者編號,姓名,位址 將編...