Python数据库API(应用程序接口)是标准Python的数据库接口。大多数Python数据库接口都遵守该标准。 Python数据库支持各种数据库服务器, 例如MySQL, GadFly, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase等。要从Python与MySQL数据库服务器连接, 我们需要导入mysql.connector接口。
下面是一个与MySQL数据库连接的程序极客.
# importing required library
import mysql.connector
# connecting to the database
dataBase = mysql.connector.connect(
host = "localhost" , user = "user" , passwd = "pswrd" , database = "geeks" )
# preparing a cursor object
cursorObject = dataBase.cursor()
# disconnecting from server
dataBase.close()
上面的程序说明了与MySQL数据库的连接极客其中主机名是本地主机, 用户名是用户密码是pswrd.
从表中删除查询
在MySQL中连接数据库后, 我们可以在其中创建表并可以对其进行操作。
语法声明:
DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE
范例1:下面是一个程序, 用于从数据库表中删除查询。
# importing required library
import mysql.connector
# connecting to the database
dataBase = mysql.connector.connect(
host = "localhost" , user = "user" , passwd = "pswrd" , database = "geeks" )
# preparing a cursor object
cursorObject = dataBase.cursor()
# creating table
studentRecord = """CREATE TABLE STUDENT (
NAME VARCHAR(20) NOT NULL, BRANCH VARCHAR(50), ROLL INT NOT NULL, SECTION VARCHAR(5), AGE INT
)"""
# table created
cursorObject.execute(studentRecord)
# inserting data into the table
query = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE) VALUES (% s, % s)"
attrValues = ( "Rituraj Saha" , "Information Technology" , "1706256" , "IT-3" , "20" )
cursorObject.execute(query, attrValues)
attrValues = ( "Ritam Barik" , "Information Technology" , "1706254" , "IT-3" , "21" )
cursorObject.execute(query, attrValues)
attrValues = ( "Rishi Kumar" , "Information Technology" , "1706253" , "IT-3" , "21" )
cursorObject.execute(query, attrValues)
# deleting query
query = "DELETE FROM STUDENT WHERE ROLL = 1706256"
cursorObject.execute(query, attrValues)
dataBase.commit()
# disconnecting from server
dataBase.close()
输出如下:
在上面的程序中, 一个名为学生创建具有属性名称, 科, 滚, 部分和年龄。将多个数据插入到学生表, 然后从具有滚属性值1706256.
范例2:让我们看一下表中查询的另一个示例。
# importing required library
import mysql.connector
# connecting to the database
dataBase = mysql.connector.connect(
host = "localhost" , user = "user" , passwd = "pswrd" , database = "geeks" )
# preparing a cursor object
cursorObject = dataBase.cursor()
# drop table if it already exists
cursorObject.execute( "DROP TABLE IF EXISTS PHONE_RECORD" )
# creating table
phoneRecord = """CREATE TABLE PHONE_RECORD (
NAME VARCHAR(20) NOT NULL, PHONE VARCHAR(10) NOT NULL
)"""
# table created
cursorObject.execute(phoneRecord)
# inserting data into the table
query = "INSERT INTO PHONE_RECORD (NAME, PHONE) VALUES (% s, % s)"
attrValues = ( "Rituraj Saha" , "9163089075" )
cursorObject.execute(query, attrValues)
# deleting query
query = "DELETE FROM STUDENT WHERE NAME = 'Rituraj Saha'"
cursorObject.execute(query)
dataBase.commit()
# disconnecting from server
dataBase.close()
输出如下:
在上面的程序中, 在极客数据库名为PHONE_RECORD具有属性名称和电话。表中仅插入一列, 然后使用删除声明。
注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。