Python MySQL示例教程

时间:2020-02-23 14:43:03  来源:igfitidea点击:

欢迎使用Python MySQL示例教程。
MySQL是使用最广泛的数据库之一,而python提供了与mysql数据库一起使用的支持。

Python MySQL

首先我们要安装python mysql连接器包。
要安装mysql软件包,请执行以下操作:转到python中的Scripts目录。

我的是:

D:\Software \ Python \ Python36-32 \ Scripts

在此处打开命令提示符。
然后输入以下命令:

D:\Software\Python\Python36-32\Scripts> pip install pymysql

数据库连接

我正在为数据库使用xampp。
这是一个可选步骤,如果您已经安装了MySQL,则可以跳过此步骤。

在开始编码之前,请运行xampp控制面板并启动Apache和MySQL。
从浏览器(https://localhost/phpmyadmin /),我创建了一个名为databaseName的数据库,如下所示:

Python MySQL示例

首先,我们必须与mysql建立连接。
以下将在python程序中连接到mysql数据库。

import pymysql

#database connection
connection = pymysql.connect(host="localhost",user="root",passwd="",database="databaseName" )
cursor = connection.cursor()
# some other statements  with the help of cursor
connection.close()

首先,我们导入了pymysql,然后建立了连接。
pymysql.connect()有四个参数。
第一个是主机名,即localhost,其余三个是声明的主机名。
使用此连接,我们创建了一个游标,该游标将用于不同的查询。

Python MySQL示例–创建表

现在,我们创建一个名为" Artist"的表格,该表格具有以下各列-名称,ID和曲目。

import pymysql

#database connection
connection = pymysql.connect(host="localhost", user="root", passwd="", database="databaseName")
cursor = connection.cursor()
# Query for creating table
ArtistTableSql = """CREATE TABLE Artists(
ID INT(20) PRIMARY KEY AUTO_INCREMENT,
NAME  CHAR(20) NOT NULL,
TRACK CHAR(10))"""

cursor.execute(ArtistTableSql)
connection.close()

将创建一个名为Artists的表。
您可以在浏览器中看到它。

Python MySQL插入

现在,我们的兴趣是在表中插入一些行实体。
首先,您必须编写查询以插入不同的数据,然后在游标的帮助下执行查询。

import pymysql

#database connection
connection = pymysql.connect(host="localhost", user="root", passwd="", database="databaseName")
cursor = connection.cursor()

# queries for inserting values
insert1 = "INSERT INTO Artists(NAME, TRACK) VALUES('Towang', 'Jazz' );"
insert2 = "INSERT INTO Artists(NAME, TRACK) VALUES('Sadduz', 'Rock' );"

#executing the quires
cursor.execute(insert1)
cursor.execute(insert2)

#commiting the connection then closing it.
connection.commit()
connection.close()

Python MySQL选择

我们在上面的代码中插入了两行。
现在我们要检索这些。
为此,请看以下示例:

import pymysql

#database connection
connection = pymysql.connect(host="localhost", user="root", passwd="", database="databaseName")
cursor = connection.cursor()

# queries for retrievint all rows
retrive = "Select * from Artists;"

#executing the quires
cursor.execute(retrive)
rows = cursor.fetchall()
for row in rows:
 print(row)

#commiting the connection then closing it.
connection.commit()
connection.close()

Python MySQL更新

假设您想将第一位艺术家的名字从Towang重命名为Tauwang。
要更新任何实体的任何属性,请执行以下操作:

updateSql = "UPDATE  Artists SET NAME= 'Tauwang'  WHERE ID = '1' ;"
cursor.execute(updateSql  )

Python MySQL删除

要删除实体,您必须执行以下操作:

deleteSql = "DELETE FROM Artists WHERE ID = '1'; "
cursor.execute(deleteSql )

Python MySQL示例–删除表

有时您可能需要在创建任何新表之前删除任何表,以免发生名称冲突。
要删除"艺术家"表,可以执行以下操作:

dropSql = "DROP TABLE IF EXISTS Artists;"
cursor.execute(dropSql)

然后,将Artists表从数据库databaseName中删除。