MySQL是最流行的关系型数据库之一,在应用开发中广泛应用。下面介绍一些开发MySQL应用的技巧。
1. 连接数据库:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
database="mydatabase"
)
print(mydb)
2. 创建表:
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
3. 插入数据:
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.")
4. 查询数据:
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
5. 更新数据:
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
6. 删除数据:
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Canyon 123'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
总结:
MySQL是一款强大的关系型数据库,开发应用时需要掌握连接、创建表、插入数据、查询数据、更新数据、删除数据等基本操作。