python和sqlite_使用Python和SQLite的SQL

在本文中,我们将学习如何在Python和SQLite数据库中使用SQL。Python有一个内置模块可与SQLite数据库连接。我们将使用sqlite3模块连接Python和SQLite。

我们必须按照以下步骤将SQLite数据库与Python连接。看一下步骤并编写程序。导入sqlite3模块。

使用sqlite3.connect(db_name)创建连接,采用数据库名称的方法是一个参数。如果不存在给定名称的文件,它将创建一个文件;否则,将打开给定名称的文件。

使用conn.cursor()从连接中获取光标对象。它是Python和SQLite数据库之间的中介。我们必须使用此光标对象来执行SQL命令。

以上三个步骤可帮助我们创建与SQLite数据库的连接。这些步骤类似于Python中的任何数据库。如果您对以上步骤有任何疑问,请参见以下代码。# importing the module

import sqlite3

# creating an connection

conn = sqlite3.connect("nhooo.db") # db - database

# Cursor object

cursor = conn.cursor()

现在,我们与数据库建立连接。通过执行以下步骤,使用SQL查询创建数据库。编写SQL代码以创建具有列名和类型的表。

使用cursor.execute()执行代码以在数据库中创建表。

编写SQL代码以在表中插入一些行。并执行与上述步骤类似的操作。

提交更改以使用conn.commit()方法将其保存在文件中。

使用conn.close()方法关闭连接。# importing the module

import sqlite3

# creating an connection

conn = sqlite3.connect("nhooo.db") # db - database

# Cursor object

cursor = conn.cursor()

# code to create a databse table

create_table_sql = """

CREATE TABLE students (

id INTEGER PRIMARY KEY,

first_name VARCHAR(20),

last_name VARCHAR(30),

gender CHAR(1)

);

"""

# executing the above SQL code

cursor.execute(create_table_sql)

# inserting data into the students table

insert_student_one_sql = """INSERT INTO students VALUES (1, "John", "Hill", "M");"""

cursor.execute(insert_student_one_sql)

insert_student_two_sql = """INSERT INTO students VALUES (2, "Jessy", "Hill", "F");"""

cursor.execute(insert_student_two_sql)

insert_student_three_sql = """INSERT INTO students VALUES (3, "Antony", "Hill", "M");"""

cursor.execute(insert_student_three_sql)

# saving the changes using commit method of connection

conn.commit()

# closing the connection

conn.close()

如果执行上述代码后没有收到任何错误,则很好。

如何从数据库表中查看数据?让我们用给定的步骤编写代码。连接到数据库。

创建一个游标对象。

编写SQL查询以从表中获取所需的数据。

现在执行它。

游标对象将具有所需的数据。使用fetchall()方法获取它。

通过打印查看数据。

如果有任何疑问,可以查看以下代码。# importing the module

import sqlite3

# creating an connection

conn = sqlite3.connect("nhooo.db") # db - database

# Cursor object

cursor = conn.cursor()

# SQL query to get all students data

fetch_students_sql = """

SELECT * FROM students;

"""

# executing the SQL query

cursor.execute(fetch_students_sql)

# storing the data in a variable using fetchall() method

students = cursor.fetchall() # a list of tuples

# printing the data

print(students)

如果执行上述程序,则将得到与输出类似的结果。

输出结果[(1, 'John', 'Hill', 'M'), (2, 'Jessy', 'Hill', 'F'), (3, 'Antony', 'Hill', 'M')]

结论

现在,您准备使用Python处理数据库。练习更多以获得更多。如果您对本教程有任何疑问,请在评论部分中提及。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值