資料庫增刪改查

2021-09-22 20:14:56 字數 1814 閱讀 3398

import pymysql

def getmysqlconn():

conn = pymysql.connect(host="172.16.238.130", port=3306, db="my_mysql", user="root", password="123456", charset="utf8")

return conn

def usersql(conn, sql):

cs = conn.cursor()

cs.execute(sql)

conn.commit()

cs.close()

conn.close()

def main():

# 建立資料的連線,編寫sql語句,增加資料

# # 建立資料庫連線,編寫sql語句,刪除資料

# conn = getmysqlconn()

# deletesql = '''delete from goods where id=11'''

# usersql(conn, deletesql)

# # 建立資料庫連線,編寫sql語句,修改資料

# conn = getmysqlconn()

# updatesql = '''update goods set name="www" where id=12'''

# usersql(conn, updatesql)

# 單條查詢

# 建立資料庫連線

conn = getmysqlconn()

# 建立游標

mycursor = conn.cursor()

# 編寫查詢sql語句

inquiresql = '''select * from goods where id=13'''

# 執行sql語句

ret = mycursor.execute(inquiresql)

# 列印查詢到的條數

print(ret)

# 從游標中拿出資料

inquiredata = mycursor.fetchall()

# 列印單條資料

print(inquiredata)

# 多條查詢

# 建立資料庫連線

conn = getmysqlconn()

# 建立游標

mycursor = conn.cursor()

# 編寫查詢sql語句

inquiresql = '''select * from goods'''

# 執行sql語句

ret = mycursor.execute(inquiresql)

# 列印查詢到的條數

print(ret)

# 獲取資料

onedata = mycursor.fetchone()

alldata = mycursor.fetchall()

# 列印獲取的資料

print(onedata)

print(alldata)

# 關閉游標及資料庫的連線

mycursor.close()

conn.close()

if __name__ == "__main__":

main()

資料庫增刪改查

我們知道當我們的表建立後重複執行會出錯,一般我們會這麼處理 create table if not exists stuinfo 學了新建表我們還應該知道乙個東西,如何刪除表 deop table table name 怎麼檢視別人的見表語句呢 show create table stuinfo 怎...

資料庫增刪改查

資料庫操作 show databases create database 資料庫名 use 資料庫名 select database drop database 資料庫名 資料表操作 create table 表名 欄位名 型別名 約束 show tables drop table 表名 資料表增刪...

資料庫增刪改查

基本語法 操作語句 create 建立 alter 更新 drop 刪除 一次性刪除乙個表中所有的資料 包括日誌 truncate table 表名 選中或者使用該資料庫 說明接下來的操作都是針對該資料庫進行 use 資料庫名稱 建立create database 資料庫名 create table...