MySQL 是一種開源的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),廣泛應(yīng)用于 Web 應(yīng)用程序開發(fā)中。無論是從事 Web 開發(fā)的初學(xué)者還是專業(yè)程序員,都需要掌握 MySQL 的基礎(chǔ)知識(shí)。本文將介紹 MySQL 編程的一些基本概念和常見操作。
連接 MySQL 數(shù)據(jù)庫
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
print(mydb)
查詢數(shù)據(jù)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
插入數(shù)據(jù)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
更新數(shù)據(jù)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = %s WHERE name = %s"
val = ("Canyon 123", "John")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
刪除數(shù)據(jù)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = %s"
val = ("Highway 21", )
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
總結(jié):
以上介紹了 MySQL 編程中的一些基礎(chǔ)概念和操作方法,希望能夠幫助大家更好地理解和應(yīng)用 MySQL。當(dāng)然,MySQL 還有很多更高級(jí)的用法,需要我們不斷學(xué)習(xí)和探索。