MySQL是一種流行的關系型數據庫,可以用來存儲和管理數據。在使用MySQL數據庫時,有一些基本的代碼需要掌握。
#連接到MySQL數據庫 import mysql.connector mydb = mysql.connector.connect( host="localhost", user="username", password="password", database="database_name" ) #創建表 mycursor = mydb.cursor() mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))") #插入數據 sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("John", "Highway 21") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.") #查詢數據 mycursor.execute("SELECT * FROM customers") myresult = mycursor.fetchall() for x in myresult: print(x) #更新數據 sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) affected") #刪除數據 sql = "DELETE FROM customers WHERE address = 'Highway 21'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted") #關閉連接 mydb.close()
通過掌握這些基本的MySQL代碼,您可以開始使用MySQL數據庫存儲和管理您的數據。