MySQL是目前最流行的關(guān)系型數(shù)據(jù)庫。以下是MySQL數(shù)據(jù)庫的增刪改查操作。
1.數(shù)據(jù)庫連接
在進(jìn)行增刪改查操作之前,需要先連接MySQL數(shù)據(jù)庫。使用以下命令進(jìn)行連接:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
2.數(shù)據(jù)庫創(chuàng)建
使用以下命令創(chuàng)建一個(gè)數(shù)據(jù)庫:
mycursor.execute("CREATE DATABASE mydatabase")
3.數(shù)據(jù)表創(chuàng)建
使用以下命令創(chuàng)建一個(gè)數(shù)據(jù)表:
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
4.數(shù)據(jù)插入
使用以下命令將數(shù)據(jù)插入到數(shù)據(jù)表中:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
5.數(shù)據(jù)查詢
使用以下命令查詢數(shù)據(jù):
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
6.數(shù)據(jù)更新
使用以下命令更新數(shù)據(jù):
sql = "UPDATE customers SET address = 'Canyon 123' WHERE name = 'John'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
7.數(shù)據(jù)刪除
使用以下命令刪除數(shù)據(jù):文章來源:http://www.zghlxwxcb.cn/news/detail-643803.html
sql = "DELETE FROM customers WHERE name = 'John'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
以上是MySQL數(shù)據(jù)庫的增刪改查操作。文章來源地址http://www.zghlxwxcb.cn/news/detail-643803.html
到了這里,關(guān)于Mysql 數(shù)據(jù)庫增刪改查的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!