pymysql資料庫之建庫建表 增刪改查

2021-09-12 23:48:03 字數 3390 閱讀 9727

上次有同學問到,python的持久化怎麼處理。這次就帶大家來體驗一下,python訪問資料庫。

python3的資料庫模組可以是pymysql。安裝可以通過pip安裝:

安裝完成後,你的python資料庫的底層依賴算是完成了。

建資料庫,庫名為awesome;建表,表名blogs;共有三列,列名 id,user_id, name

import pymysql

# 建庫和建表

con = pymysql.connect(host=

'localhost'

, user=

'root'

, passwd=

'123456'

, charset=

'utf8'

)cur = con.cursor(

)# 開始建庫

cur.execute(

"create database awesome character set utf8;"

)# 使用庫

cur.execute(

"use awesome;"

)# 建表

cur.execute(

"create table blogs(id char(20),user_id char(20),name char(20),)character set utf8;"

)

查詢表,表名blogs

# 1.建立連線,使用者root 密碼mysql123456 dbname:awesome

db = pymysql.connect(

"localhost"

,"root"

,"mysql123456"

,"awesome"

)# 獲取游標

cur = db.cursor(

)# sql查詢語句 表名blogs

sql =

"select * from blogs"

try:

cur.execute(sql)

# 執行sql語句

results = cur.fetchall(

)# 獲取查詢的所有記錄

print

("id"

,"user_id"

,"name"

)# 遍歷結果

for row in results:

id= row[0]

user_id = row[1]

name = row[4]

print(id

, name, user_id)

except exception as e:

raise e

finally

: db.close(

)# 關閉連線

往表blog裡插入一行資料(id,user_id,name) = (「test_id」,『test_user_id』,『test_name』)

# 2.插入操作

db = pymysql.connect(

"localhost"

,"root"

,"mysql12345"

,"awesome"

)cur_insert = db.cursor(

)# sql插入語句 表名blogs

sql_insert =

"""insert into blogs(id,user_id,name) values ("test_id",'test_user_id','test_name')"""

try:

cur_insert.execute(sql_insert)

# 提交

db.commit(

)print

('開始資料庫插入操作'

)except exception as e:

db.rollback(

)print

('資料庫插入操作錯誤回滾'

)finally

: db.close(

)

更新user_id = 「test_user_id」 的行,將其 name 更新為 「update_test_name」

# 3.更新操作

db = pymysql.connect(

"localhost"

,"root"

,"mysql12345"

,"awesome"

)cur_update = db.cursor(

)sql_update =

"update awesome.blogs set name = '%s' where user_id = '%s'"

try:

cur_update.execute(sql_update %

("update_test_name"

,"test_user_id"))

# 提交

db.commit(

)print

('開始資料庫更新操作'

)except exception as e:

db.rollback(

)print

('資料庫更新操作錯誤回滾'

)finally

: db.close(

)

刪除 name = 「update_test_name」 的行

# 4.刪除操作

db = pymysql.connect(

"localhost"

,"root"

,"mysql12345"

,"awesome"

)cur_delete = db.cursor(

)sql_delete =

"delete from awesome.blogs where name = '%s'"

try:

cur_delete.execute(sql_delete %

("update_test_name"))

# 像sql語句傳遞引數

# 提交

db.commit(

)print

('開始資料庫刪除操作'

)except exception as e:

db.rollback(

)print

('資料庫刪除操作錯誤回滾'

)finally

: db.close(

)

這裡以mysql為例,如果使用mongodb等其他資料庫,使用方法也是類似的,大家可以舉一反三。

Oracle資料庫 建庫 建表空間,建使用者

oracle資料庫 建庫 建表空間,建使用者 oracle安裝完後,其中有乙個預設的資料庫,除了這個預設的資料庫外,我們還可以建立自己的資料庫。對於初學者來說,為了避免麻煩,可以用 database configuration assistant 嚮導來建立資料庫。建立完資料庫後,並不能立即在資料庫...

Oracle資料庫 建庫 建表空間,建使用者

oracle安裝完後,其中有乙個預設的資料庫,除了這個預設的資料庫外,我們還可以建立自己的資料庫。對於初學者來說,為了避免麻煩,可以用 database configuration assistant 嚮導來建立資料庫。建立完資料庫後,並不能立即在資料庫中建表,必須先建立該資料庫的使用者,並且為該使...

Oracle資料庫 建庫 建表空間,建使用者

oracle安裝完後,其中有乙個預設的資料庫,除了這個預設的資料庫外,我們還可以建立自己的資料庫。對於初學者來說,為了避免麻煩,可以用 database configuration assistant 嚮導來建立資料庫。建立完資料庫後,並不能立即在資料庫中建表,必須先建立該資料庫的使用者,並且為該使...