Python3 implements a method to connect to a SQLite database

  • 2020-04-02 14:01:16
  • OfStack

This paper illustrates the method of connection with SQLite database in Python3. Share with you for your reference. Specific methods are as follows:

Example code is as follows:


import sqlite3

db = r"D:pyWorktest.db"  #pyWork directory test.db Database file 
drp_tb_sql = "drop table if exists staff"
crt_tb_sql = """
create table if not exists staff(
  id integer primary key autoincrement unique not null,
  name varchar(100),
  city varchar(100)
);
"""

# Connect to database 
con = sqlite3.connect(db)
cur = con.cursor()

# Create a table staff
cur.execute(drp_tb_sql)
cur.execute(crt_tb_sql)

# Insert records 
insert_sql = "insert into staff (name,city) values (?,?)"  #? As a placeholder 
cur.execute(insert_sql,('Tom','New York'))
cur.execute(insert_sql,('Frank','Los Angeles'))
cur.execute(insert_sql,('Kate','Chicago'))
cur.execute(insert_sql,('Thomas','Houston'))
cur.execute(insert_sql,('Sam','Philadelphia'))

con.commit()

# Query log 
select_sql = "select * from staff"
cur.execute(select_sql)

# Returns a list . list The object type is tuple (a tuple) 
date_set = cur.fetchall()
for row in date_set:
  print(row)

cur.close()
con.close()

I hope this example has helped you with your Python learning.


Related articles: