天天看點

連接配接資料庫,并進行基礎的增删改查

import pymysql

# 連接配接資料庫
# pymysql.connect("資料庫伺服器位址", "使用者名", "密碼", "庫名", charset='utf-8')
database = pymysql.connect("127.0.0.1", "root", "123456", "mysql", charset='utf-8')
# 初始化指針
cursor = database.cursor()

# 增加資料
# 格式:"INSERT INTO 表明 (字段1,字段2,字段3) VALUES ('内容1','内容2','内容3');"
sql = "INSERT INTO date (date,company,private,price,weight) VALUES ('2019-9-20','河北糧食','河北','2200','35.1');"
cursor.execute(sql)
# 對存儲的資料修改後,需要commit
database.commit()
database.close()

# 修改資料
# 格式:"UPDATE 表名 SET 字段1=内容1,字段2=内容2 where 條件;"
sql1 = "UPDATE data SET date='2018-09-21' where date='2019-02-21';"
cursor.execute(sql1)
database.commit()
database.close()

# 查詢資料
# 格式:"SELECT 字段 FROM 表名 WHERE 條件;"
sql2 = "SELECT company,price FROM date WHERE date='2019-02-21';"
cursor.execute(sql2)
result = cursor.fetchall()
print(result)

# 删除資料
# 格式:"DELETE FROM 表名 WHERE 條件;"
sql3 = "DELETE FROM data WHERE date='2018-08-08';"
cursor.execute(sql3)
database.commit()
database.close()