使用Python的SQL

本文讨论了SQLite3与Python的集成。这里我们将使用Python讨论SQLite3数据库上的所有CRUD操作。CRUD包含四项主要操作:

null

CRUD operations SQLite3 and Python

注: 这需要基本了解 SQL .

在这里,我们将用Python连接SQLite。Python有一个用于SQLite3的本机库,名为 sqlite3 .让我们解释一下它是如何工作的。

连接到SQLite数据库

  • 要使用SQLite,我们必须导入 sqlite3 .
import sqlite3
  • 然后使用 连接() 方法并传递要访问的数据库的名称。如果有具有该名称的文件,它将打开该文件。否则,Python将创建一个具有给定名称的文件。
sqliteConnection = sqlite3.connect('gfg.db')
  • 在此之后,将调用游标对象,以便能够向SQL发送命令。
cursor = sqliteConnection.cursor()

示例:使用Python连接到SQLite3数据库

Python3

import sqlite3
# connecting to the database
connection = sqlite3.connect( "gfg.db" )
# cursor
crsr = connection.cursor()
# print statement will execute if there
# are no errors
print ( "Connected to the database" )
# close the connection
connection.close()


输出:

Connected to the database

光标对象

在进一步讨论SQLite3和Python之前,让我们先讨论一下 光标对象 简言之

  • 游标对象用于建立用于执行SQL查询的连接。
  • 它充当SQLite数据库连接和SQL查询之间的中间件。它是在连接到SQLite数据库后创建的。
  • 游标是一种控制结构,用于遍历和获取数据库的记录。
  • 所有命令将仅使用游标对象执行。

执行SQLite3查询–创建表

在连接到数据库并创建游标对象之后,让我们看看如何执行查询。

  • 要在数据库中执行查询,请创建一个对象,并在其中编写带有注释的SQL命令。示例:-sql_comm=“sql语句”
  • 执行命令非常容易。调用游标方法execute(),并将sql命令的名称作为参数传递给它。将大量命令另存为sql_comm并执行它们。执行所有活动后,通过提交这些更改来保存文件中的更改,然后断开连接。

示例:使用Python创建SQLite3表

在本例中,我们将 使用Python创建SQLite3表 .标准SQL命令将用于创建表。

python

import sqlite3
# connecting to the database
connection = sqlite3.connect( "gfg.db" )
# cursor
crsr = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE emp (
staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE);"""
# execute the statement
crsr.execute(sql_command)
# close the connection
connection.close()


输出:

python sqlite3 create table

插入表格

插入数据 我们将再次将SQL命令作为字符串写入表中,并使用execute()方法。

示例1:使用Python将数据插入SQLite3表

Python3

# Python code to demonstrate table creation and
# insertions with SQL
# importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect( "gfg.db" )
# cursor
crsr = connection.cursor()
# SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (23, "Rishabh",
"Bansal", "M", "2014-03-28");"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO emp VALUES (1, "Bill", "Gates",
"M", "1980-10-28");"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()


输出:

python sqlite3 insert data

示例2:插入用户输入的数据

Python3

# importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect( "gfg.db" )
# cursor
crsr = connection.cursor()
# primary key
pk = [ 2 , 3 , 4 , 5 , 6 ]
# Enter 5 students first names
f_name = [ 'Nikhil' , 'Nisha' , 'Abhinav' , 'Raju' , 'Anshul' ]
# Enter 5 students last names
l_name = [ 'Aggarwal' , 'Rawat' , 'Tomar' , 'Kumar' , 'Aggarwal' ]
# Enter their gender respectively
gender = [ 'M' , 'F' , 'M' , 'M' , 'F' ]
# Enter their jpining data respectively
date = [ '2019-08-24' , '2020-01-01' , '2018-05-14' , '2015-02-02' , '2018-05-14' ]
for i in range ( 5 ):
# This is the q-mark style:
crsr.execute(f 'INSERT INTO emp VALUES ({pk[i]}, "{f_name[i]}", "{l_name[i]}", "{gender[i]}", "{date[i]}")' )
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()


输出:

insert into table python sqlite3

获取数据

在本节中,我们讨论了如何创建表以及如何在数据库中添加新行。 获取数据 从记录中插入数据很简单。execute方法使用SQL命令,使用“Select*from table_name”从表中获取所有数据,所有表数据都可以以列表的形式在对象中获取。

示例:使用Python从sqlite3表读取数据

python

# importing the module
import sqlite3
# connect withe the myTable database
connection = sqlite3.connect( "gfg.db" )
# cursor object
crsr = connection.cursor()
# execute the command to fetch all the data from the table emp
crsr.execute( "SELECT * FROM emp" )
# store all the fetched data in the ans variable
ans = crsr.fetchall()
# Since we have already selected all the data entries
# using the "SELECT *" SQL command and stored them in
# the ans variable, all we need to do now is to print
# out the ans variable
for i in ans:
print (i)


输出:

fetch data python sqlite3

注: 需要注意的是,将要创建的数据库文件将与python文件位于同一文件夹中。如果要更改文件的路径,请在打开文件时更改路径。

更新数据

对于 更新数据 在SQLite3表中,我们将使用UPDATE语句。我们可以根据需要使用update语句更新单列和多列。

UPDATE table_name SET column1 = value1, column2 = value2,…  
WHERE condition; 

在上述语法中,SET语句用于为特定列设置新值,WHERE子句用于选择需要更新列的行。

示例:使用Python更新SQLite3表

Python3

# Import module
import sqlite3
# Connecting to sqlite
conn = sqlite3.connect( 'gfg.db' )
# Creating a cursor object using
# the cursor() method
cursor = conn.cursor()
# Updating
cursor.execute( '''UPDATE emp SET lname = "Jyoti" WHERE fname="Rishabh";''' )
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()


输出:

update sqlite3 table using Python

删除数据

对于 删除数据 从SQLite3表中,我们可以使用delete命令。

DELETE FROM table_name [WHERE Clause]

示例:使用Python从SQLite3表中删除

Python3

# Import module
import sqlite3
# Connecting to sqlite
conn = sqlite3.connect( 'gfg.db' )
# Creating a cursor object using
# the cursor() method
cursor = conn.cursor()
# Updating
cursor.execute( '''DELETE FROM emp WHERE fname="Rishabh";''' )
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()


输出:

Deleting from SQLite3 table using Python

删除表

DROP用于删除整个数据库或表。它删除了表中的两条记录以及表结构。

语法:

DROP TABLE TABLE_NAME;

示例:使用Python删除SQLite3表

gfg中的总表格。下降前的db

drop sqlite3 table using Python

现在让我们删除学生表,然后再次检查数据库中的total表。

Python3

# Import module
import sqlite3
# Connecting to sqlite
conn = sqlite3.connect( 'gfg.db' )
# Creating a cursor object using
# the cursor() method
cursor = conn.cursor()
# Updating
cursor.execute( '''DROP TABLE Student;''' )
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()


输出:

Dropping SQLite3 table using Python

注: 要了解有关SQLit3与Python的更多信息,请参阅我们的 Python SQLite3 辅导的

本文由 里沙布·班萨尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享