mysql数据剪切到新表_第17章:Python数据库

0037c47cf7a8a5e471a147cead004a9c.png

Python MySQL环境配置

简介

Python MySQL环境配置,要将python应用程序与MySQL数据库连接,我们必须在程序中导入mysql.connector模块,使用MySQL的连接模块进行连接。


环境设置

要构建真实世界的应用程序,与数据库连接是编程语言的必要条件。但是,python允许我们将应用程序连接到MySQL,SQLite,MongoDB等许多数据库。

在本教程的这一部分中,我们将讨论Python - MySQL连接,我们将在python中执行数据库操作。我们还将在本教程后面介绍与MongoDB和SQLite等数据库的Python连接。

安装mysql.connector

要将python应用程序与MySQL数据库连接,我们必须在程序中导入mysql.connector模块。

mysql.connector不是python安装附带的内置模块。我们需要安装它以使其正常工作。

执行以下命令以使用pip安装程序进行安装。

> python -m pip install mysql-connector

或者按照以下步骤操作。

1.单击链接:

https://files.pythonhosted.org/packages/8f/6d/fb8ebcbbaee68b172ce3dfd08c7b8660d09f91d8d5411298bcacbd309f96/mysql-connector-python-8.0.13.tar.gz下载源代码。

2.提取存档文件。

3.打开终端(CMD for windows)并将当前工作目录更改为源代码目录。

$ cd mysql-connector-python- 8.0 。13 /

4.使用python(python3,如果你还安装了python 2)运行带有参数build的名为setup.py的文件。

$ python setup.py构建

5.运行以下命令以安装mysql-connector。

$ python setup.py安装

这将需要一些时间来安装python的mysql-connector。通过在python shell上导入mysql-connector,我们可以在进程结束后验证安装。

27a1bc353256b9a7a04511826a77868f.png

因此,我们已经在我们的系统上成功安装了python的mysql-connector

Python MySQL连接访问

简介

安装和导入mysql.connector模块后就可以进行数据的连接,创建完连接对象和游标对象后就可以使用对象进行查询操作。


将python应用程序连接到数据库有以下步骤。

导入mysql.connector模块

创建连接对象。

创建游标对象

执行查询

创建连接

要在MySQL数据库和python应用程序之间创建连接,请使用mysql.connector模块的connect()方法。

在方法调用中传递数据库详细信息,如HostName,username和数据库密码。该方法返回连接对象。

下面给出了使用connect()的语法。

Connection-Object = mysql.connector.connect(host = ,user = ,passwd = )

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  #printing the connection object   print(myconn)

Output:

在这里,我们必须注意,如果我们想连接到特定的数据库,我们可以在connect()方法中指定数据库名称。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")  #printing the connection object   print(myconn)

输出:

创建游标对象

游标对象可以定义为Python DB-API 2.0中指定的抽象。它通过与数据库的相同连接促进了我们拥有多个独立的工作环境。我们可以通过调用连接对象的'cursor'函数来创建游标对象。游标对象是对数据库执行查询的重要方面。

下面给出了创建游标对象的语法。

 = conn.cursor()

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")  #printing the connection object   print(myconn)   #creating the cursor object  cur = myconn.cursor()  print(cur)

输出:

MySQLCursor: (Nothing executed yet)

Python MySQL创建数据库

简介

安装和导入mysql.connector模块后就可以进行数据的连接,创建完连接对象和游标对象后就可以使用对象进行查询操作。


我们将创建新的数据库PythonDB。

获取现有数据库的列表

我们可以使用以下MySQL查询获取所有数据库的列表。

>  show databases;

案例:

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  #creating the cursor object  cur = myconn.cursor()  try:      dbs = cur.execute("show databases")  except:      myconn.rollback()  for x in cur:      print(x)  myconn.close()

输出:

('EmployeeDB',)('Test',)('TestDB',)('information_schema',)('javatpoint',)('javatpoint1',)('mydb',)('mysql',)('performance_schema',)('testDB',)

创建新数据库

可以使用以下SQL查询创建新数据库。

>  create database 

案例:

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")  #creating the cursor object  cur = myconn.cursor()  try:      #creating a new database      cur.execute("create database PythonDB2")      #getting the list of all the databases which will now include the new database PythonDB      dbs = cur.execute("show databases")  except:      myconn.rollback()  for x in cur:          print(x)  myconn.close()

输出:

('EmployeeDB',)('PythonDB',)('Test',)('TestDB',)('anshika',)('information_schema',)('javatpoint',)('javatpoint1',)('mydb',)('mydb1',)('mysql',)('performance_schema',)('testDB',)

Python MySQL创建表格

简介

我们可以使用SQL的CREATE TABLE语句创建新表。在我们的数据库PythonDB中,Employee表最初将包含四列,即name,id,salary和department_id。


在本教程的这一部分中,我们将创建新表Employee。我们必须在建立连接对象时提及数据库名称。

我们可以使用SQL的CREATE TABLE语句创建新表。在我们的数据库PythonDB中,Employee表最初将包含四列,即name,id,salary和department_id。

以下查询用于创建新表Employee。

>  create table Employee (name varchar(20) not null, id int primary key, salary float not null, Dept_Id int not null)

Example

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Creating a table with name Employee having four columns i.e., name, id, salary, and department id      dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key, salary float not null, Dept_id int not null)")  except:      myconn.rollback()  myconn.close()

6770116e7b4e07a46a380623a5ab28ea.png

现在,我们可以检查表Employee是否存在于数据库中。

改变表

有时,我们可能忘记创建一些列,或者我们可能需要更新表模式。如果需要,alter语句用于更改表模式。在这里,我们将列branch_name添加到表Employee中。以下SQL查询用于此目的。

alter table Employee add branch_name varchar(20 )  not  null

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #adding a column branch name to the table Employee      cur.execute("alter table Employee add branch_name varchar(20) not null")  except:      myconn.rollback()  myconn.close()

74ee384e8d0700ddc8a4d43b94bc28d1.png

Python MySQL插入操作

简介

该INTO INSERT语句用来记录添加到表。在python中,我们可以提到格式说明符(%s)来代替值。我们在游标的execute()方法中以元组的形式提供实际值。


插入操作

向表中添加记录

该INTO INSERT语句用来记录添加到表。在python中,我们可以提到格式说明符(%s)来代替值。

我们在游标的execute()方法中以元组的形式提供实际值。

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  #The row values are provided in the form of tuple   val = ("John", 110, 25000.00, 201, "Newyork")  try:      #inserting the values into the table      cur.execute(sql,val)      #commit the transaction       myconn.commit()  except:      myconn.rollback()  print(cur.rowcount,"record inserted!")  myconn.close()

输出:

1 record inserted!

703596b4c09e174a933178700bee65f3.png

插入操作

插入多行

我们也可以使用python脚本一次插入多行。提到多行作为各种元组的列表。

列表的每个元素都被视为一个特定的行,而元组的每个元素都被视为一个特定的列值(属性)。

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("Nick",104,90000.00,201,"Newyork")]  try:      #inserting the values into the table      cur.executemany(sql,val)      #commit the transaction       myconn.commit()      print(cur.rowcount,"records inserted!")  except:      myconn.rollback()  myconn.close()

输出:

3 records inserted!

f5f4f2f43dda671e1deea9e46ccd2af2.png

插入操作

行ID

在SQL中,特定行由插入标识表示,该标识称为行标识。我们可以使用游标对象的属性lastrowid来获取最后插入的行id。

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  val = ("Mike",105,28000,202,"Guyana")  try:      #inserting the values into the table      cur.execute(sql,val)      #commit the transaction       myconn.commit()      #getting rowid      print(cur.rowcount,"record inserted! id:",cur.lastrowid)  except:      myconn.rollback()  myconn.close()

输出:

1 record inserted! Id: 0

Python MySQL读取操作

简介

SELECT 语句被用来从数据库中读取这些值。我们可以限制该输出的选择通过使用各种查询子句在 SQL 等、限制等。Python 提供 FETCHALL () 方法返回的数据存储在表的行。我们可以重复的结果以得到单个行。


读取操作

SELECT 语句被用来从数据库中读取这些值。我们可以限制该输出的选择通过使用各种查询子句在 SQL 等、限制等。

Python 提供 FETCHALL ()方法返回的数据存储在表的行。我们可以重复的结果以得到单个行。

在本节教程中 , 我们将从数据库提取的数据通过使用 Python 脚本。我们也将它输出至格式打印到控制台。

实例

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select * from Employee")      #fetching the rows from the cursor object      result = cur.fetchall()      #printing the result      for x in result:          print(x);  except:      myconn.rollback()  myconn.close()

输出 :

('John', 101, 25000.0, 201, 'Newyork')('John', 102, 25000.0, 201, 'Newyork')('David', 103, 25000.0, 202, 'Port of spain')('Nick', 104, 90000.0, 201, 'Newyork')('Mike', 105, 28000.0, 202, 'Guyana')

不同列的读取

我们可以通过特定的读出列提及他们的名字 , 而不是使用星 (*) 。

在以下的例子中 , 将读出的名称、 ID 、和从雇员薪金表 , 并将其打印到控制台。

实例

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee")      #fetching the rows from the cursor object      result = cur.fetchall()      #printing the result      for x in result:          print(x);  except:      myconn.rollback()  myconn.close()

输出 :

('John', 101, 25000.0)('John', 102, 25000.0)('David', 103, 25000.0)('Nick', 104, 90000.0)('Mike', 105, 28000.0)

fetchone () 方法

在 fetchone () 方法用于只获取一个列的表。fetchone ()方法返回的下一个行的结果集合。

考虑以下示例。

实例

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee")      #fetching the first row from the cursor object      result = cur.fetchone()      #printing the result      print(result)  except:      myconn.rollback()  myconn.close()

输出 :

('John', 101, 25000.0)

格式化结果

我们可以通过迭代格式的结果产生的结果或fetchone FETCHALL ()() 方法的结果存在由于光标对象 , 该元组对象不可读。

考虑以下示例。

实例

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee")      #fetching the rows from the cursor object      result = cur.fetchall()      print("Name    id    Salary");      for row in result:          print("%s    %d    %d"%(row[0],row[1],row[2]))  except:      myconn.rollback()  myconn.close()

输出 :

Name    id    SalaryJohn    101    25000John    102    25000David    103    25000Nick    104    90000Mike    105    28000

使用 WHERE 子句

我们能限制所产生的结果与通过使用 SELECT 语句 WHERE 子句。这将仅仅提取那些列满足 WHERE 条件。

考虑以下示例。

示例 :姓名从J开始

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee where name like 'J%'")      #fetching the rows from the cursor object      result = cur.fetchall()      print("Name    id    Salary");      for row in result:          print("%s    %d    %d"%(row[0],row[1],row[2]))  except:      myconn.rollback()  myconn.close()

输出 :

Name    id    SalaryJohn    101    25000John    102    25000

示例 :姓名和 ID = 101 、 102 和 103

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee where id in (101,102,103)")      #fetching the rows from the cursor object      result = cur.fetchall()      print("Name    id    Salary");      for row in result:          print("%s    %d    %d"%(row[0],row[1],row[2]))  except:      myconn.rollback()  myconn.close()

输出 :

Name    id    SalaryJohn    101    25000John    102    25000David    103    2500

结果排序

ORDER BY 子句中使用命令的结果。考虑以下示例。

实例

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee order by name")      #fetching the rows from the cursor object      result = cur.fetchall()      print("Name    id    Salary");      for row in result:          print("%s    %d    %d"%(row[0],row[1],row[2]))  except:      myconn.rollback()  myconn.close()

输出 :

Name    id    SalaryDavid   103    25000John    101    25000John    102    25000Mike    105    28000Nick    104    90000

Order By DESC

此命令的结果而在特定列。

实例

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Reading the Employee data          cur.execute("select name, id, salary from Employee order by name desc")      #fetching the rows from the cursor object      result = cur.fetchall()      #printing the result      print("Name    id    Salary");      for row in result:          print("%s    %d    %d"%(row[0],row[1],row[2]))  except:      myconn.rollback()  myconn.close()

输出 :

Name    id    SalaryNick    104    90000Mike    105    28000John    101    25000John    102    25000David    103    25000

Python MySQL更新操作

简介

UPDATE-SET语句用于更新表中的任何列。以下SQL查询用于更新列。DELETE FROM语句用于从表中删除特定记录。


更新操作

UPDATE-SET语句用于更新表中的任何列。以下SQL查询用于更新列。

>  update Employee set name = 'alex' where id = 110

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #updating the name of the employee whose id is 110      cur.execute("update Employee set name = 'alex' where id = 110")      myconn.commit()  except:      myconn.rollback()  myconn.close()

71a421ce9c44b7a0ff9601a42715fe8b.png

更新操作

删除操作

DELETE FROM语句用于从表中删除特定记录。在这里,我们必须使用WHERE子句强加条件,否则将删除表中的所有记录。

以下SQL查询用于从表中删除id为110的员工详细信息。

>  delete from Employee where id = 110

请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #Deleting the employee details whose id is 110      cur.execute("delete from Employee where id = 110")      myconn.commit()  except:      myconn.rollback()  myconn.close()

Python MySQL连接操作

简介

我们可以使用join语句通过使用其中的一些公共列来组合两个或多个表中的列,右连接显示右侧表的所有列,左连接覆盖左侧表中的所有数据,它与右连接的效果正好相反。


我们可以使用join语句通过使用其中的一些公共列来组合两个或多个表中的列。

我们的数据库中只有一个表,让我们再创建一个包含两列department_id和department_name的表Departments。

create table Departments (Dept_id int(20) primary key not null, Dept_Name varchar(20) not null);

4cbef9b83d09a9c8767f9a70c304c7ad.png

连接操作

正如我们创建了一个新表Departments,如上图所示。但是,我们还没有在其中插入任何值。

让我们插入一些Departments ID和部门名称,以便我们可以将其映射到Employee表。

insert into Departments values (201, "CS");  insert into Departments values (202, "IT");

让我们看一下每个表中插入的值。请考虑以下图像。

79e4b5c63c5253160e1dd2fc3bf3631b.png

现在,让我们创建一个python脚本,连接公共列上的两个表,即dept_id。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #joining the two tables on departments_id      cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id, Departments.Dept_Name from Departments join Employee on Departments.Dept_id = Employee.Dept_id")      print("ID    Name    Salary    Dept_Id    Dept_Name")      for row in cur:          print("%d    %s    %d    %d    %s"%(row[0], row[1],row[2],row[3],row[4]))  except:      myconn.rollback()  myconn.close()

输出:

ID    Name    Salary    Dept_Id    Dept_Name101   John    25000    201    CS102   John    25000    201    CS103   David   25000       202    IT104   Nick    90000   201    CS105   Mike    28000   202   IT

右连接

右连接显示右侧表的所有列,因为我们在数据库PythonDB中有两个表,即Departments和Employee。表中没有任何不在任何部门工作的员工(部门ID为null的员工)。但是,为了理解右连接的概念,让我们创建一个。

在MySQL服务器上执行以下查询。

insert into Employee(name, id, salary, branch_name) values ("Alex",108,29900,"Mumbai");

这将插入一个不适用于任何部门的员工Alex(部门ID为空)。

现在,我们在Employee表中有一个员工,其部门ID不在Departments表中。现在让我们在两个表上执行正确的连接。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #joining the two tables on departments_id      result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id, Departments.Dept_Name from Departments right join Employee on Departments.Dept_id = Employee.Dept_id")      print("ID    Name    Salary    Dept_Id    Dept_Name")      for row in cur:          print(row[0],"    ", row[1],"    ",row[2],"    ",row[3],"    ",row[4])  except:      myconn.rollback()  myconn.close()

输出:

ID    Name    Salary    Dept_Id    Dept_Name101      John      25000.0      201      CS102      John      25000.0      201      CS103      David      25000.0      202      IT104      Nick      90000.0      201      CS105      Mike      28000.0      202      IT108      Alex      29900.0      None      None

左连接

左连接覆盖左侧表中的所有数据。它与右连接的效果正好相反。请考虑以下示例。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      #joining the two tables on departments_id      result = cur.execute("select Employee.id, Employee.name, Employee.salary, Departments.Dept_id, Departments.Dept_Name from Departments left join Employee on Departments.Dept_id = Employee.Dept_id")      print("ID    Name    Salary    Dept_Id    Dept_Name")      for row in cur:          print(row[0],"    ", row[1],"    ",row[2],"    ",row[3],"    ",row[4])  except:      myconn.rollback()  myconn.close()

输出:

ID    Name    Salary    Dept_Id    Dept_Name101      John      25000.0      201      CS102      John      25000.0      201      CS103      David      25000.0      202      IT104      Nick      90000.0      201      CS105      Mike      28000.0      202      IT

Python MySQL事务执行

简介

事务确保数据库的数据一致性。我们必须确保多个应用程序在执行数据库操作时不得修改记录。事务具有以下属性、原子性、一致性、隔离性、持久性。


执行事务

事务确保数据库的数据一致性。我们必须确保多个应用程序在执行数据库操作时不得修改记录。事务具有以下属性。

原子性

事务完成或没有任何反应。如果事务包含4个查询,则必须执行所有这些查询,否则不能执行任何查询。

一致性

数据库必须在事务启动之前保持一致,并且数据库在事务完成后也必须保持一致。

隔离性

事务的中间结果在当前事务之外是不可见的。

持久性

一旦提交了事务,即使系统出现故障,影响也会持续存在。

Python commit()方法

Python提供了commit()方法,该方法确保对其进行更改

数据库始终如一。

下面给出了使用commit()方法的语法。

conn.commit()  #conn是连接对象

在调用commit()之前,不会进行修改数据库记录的所有操作。

Python rollback()方法

rollback()方法用于还原对数据库所做的更改。此方法很有用,如果在数据库操作期间发生某些错误,我们可以回滚该事务以维护数据库一致性。

下面给出了使用rollback()的语法。

Conn.rollback()

关闭连接

完成有关数据库的所有操作后,我们需要关闭数据库连接。Python提供了close()方法。下面给出了使用close()方法的语法。

conn.close()

在以下示例中,我们将删除所有为CS部门工作的员工。

import mysql.connector  #Create the connection object   myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",database = "PythonDB")  #creating the cursor object  cur = myconn.cursor()  try:      cur.execute("delete from Employee where Dept_id = 201")      myconn.commit()      print("Deleted !")  except:      print("Can't delete !")      myconn.rollback()  myconn.close()

输出:

Deleted !

Python SQLite数据库使用

简介

SQLite是一种嵌入式数据库,它的数据库就是一个文件。Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。


SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOS和Android的App中都可以集成。

Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。

在使用SQLite前,我们先要搞清楚几个概念:

表是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,比如学生的表,班级的表,学校的表,等等。表和表之间通过外键关联。

要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection;

连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。

由于SQLite的驱动内置在Python标准库中,所以我们可以直接来操作SQLite数据库。

我们在Python交互式命令行实践一下:

# 导入SQLite驱动:>>> import sqlite3# 连接到SQLite数据库# 数据库文件是test.db# 如果文件不存在,会自动在当前目录创建:>>> conn = sqlite3.connect('test.db')# 创建一个Cursor:>>> cursor = conn.cursor()# 执行一条SQL语句,创建user表:>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')# 继续执行一条SQL语句,插入一条记录:>>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')# 通过rowcount获得插入的行数:>>> cursor.rowcount1# 关闭Cursor:>>> cursor.close()# 提交事务:>>> conn.commit()# 关闭Connection:>>> conn.close()

我们再试试查询记录:

>>> conn = sqlite3.connect('test.db')>>> cursor = conn.cursor()# 执行查询语句:>>> cursor.execute('select * from user where id=?', ('1',))# 获得查询结果集:>>> values = cursor.fetchall()>>> values[('1', 'Michael')]>>> cursor.close()>>> conn.close()

使用Python的DB-API时,只要搞清楚ConnectionCursor对象,打开后一定记得关闭,就可以放心地使用。

使用Cursor对象执行insert,updatedelete语句时,执行结果由rowcount返回影响的行数,就可以拿到执行结果。

使用Cursor对象执行select语句时,通过featchall()可以拿到结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录。

如果SQL语句带有参数,那么需要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:

cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))

SQLite支持常见的标准SQL语句以及几种常见的数据类型。具体文档请参阅SQLite官方网站。

tips:

在Python中操作数据库时,要先导入数据库对应的驱动,然后,通过Connection对象和Cursor对象操作数据。

要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。

如何才能确保出错的情况下也关闭掉Connection对象和Cursor对象呢?请回忆try:...except:...finally:...的用法。

练习

请编写函数,在Sqlite中根据分数段查找指定的名字:

# -*- coding: utf-8 -*-import os, sqlite3db_file = os.path.join(os.path.dirname(__file__), 'test.db')if os.path.isfile(db_file):    os.remove(db_file)# 初始数据:conn = sqlite3.connect(db_file)cursor = conn.cursor()cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")cursor.close()conn.commit()conn.close()def get_score_in(low, high):    ' 返回指定分数区间的名字,按分数从低到高排序 '    pass# 测试:assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)print('Pass')

END

时光,在物转星移中渐行渐远,春花一梦,流水无痕,没有在最想做的时候去做的事情,都是人生的遗憾。人生需要深思熟虑,也需要一时的冲动。

5c5ea83b335193396f5f9c42ea8a168b.gif

c5b9b95745f4d31d6bb597b9bce1921c.png

5c5ea83b335193396f5f9c42ea8a168b.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值