Python数据库操作函数实用宝典
发布时间:2023-06-10 02:43:41
Python是一种广泛使用的编程语言,它具有易学易用的特点,因此在数据科学和机器学习领域广受欢迎。与此同时,数据库操作也是Python的一个重要领域之一。
Python数据库操作涉及到访问和处理数据库中的数据,包括连接、查询、插入、更新和删除等操作。以下是一些常用的Python数据库操作函数:
1.连接数据库
Python提供了许多用于连接数据库的模块和库,其中最常用的是mysql和pymysql。
*使用mysql连接数据库
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" )
*使用pymysql连接数据库
import pymysql mydb = pymysql.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" )
2.创建数据表
在Python中,使用execute()函数执行SQL语句以创建数据表。
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
3.插入数据
使用execute()函数执行SQL语句以插入数据。
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.查询数据
使用execute()函数执行SQL语句以查询数据。
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
5.更新数据
使用execute()函数执行SQL语句以更新数据。
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) affected")
6.删除数据
使用execute()函数执行SQL语句以删除数据。
sql = "DELETE FROM customers WHERE address = 'Mountain 21'" mycursor.execute(sql) mydb.commit() print(mycursor.rowcount, "record(s) deleted")
7.关闭连接
使用close()函数关闭数据库连接。
mydb.close()
在Python中,我们可以使用这些常用的数据库操作函数来连接到数据库,创建表格,插入,查询,更新和删除数据。这些函数能够帮助我们对数据进行快速有效的处理,在数据科学和机器学习等领域具有广泛的应用。
