Python3 to implement the method of connecting SQLite database _python

Source: Internet
Author: User
Tags sqlite sqlite database

This article illustrates the method of Python3 to realize the connection of SQLite database, which has good reference value for Python learning. Share for everyone to use for reference. The specific methods are as follows:

The instance code is as follows:

Import sqlite3

db = r "D:\pyWork\test.db"  #pyWork目录下test. db database file
drp_tb_sql = "DROP table if exists staff" C4/>crt_tb_sql = "" "
create table if not EXISTS staff (
  ID integer primary key autoincrement unique NOT NULL,
  n Ame varchar (m), City
  varchar ()
);

"" #连接数据库
con = sqlite3.connect (db)
cur = con.cursor ()

#创建表staff
cur.execute (drp_tb_sql)
Cur.execute (crt_tb_sql)

#插入记录
insert_sql = "INSERT into staff (name,city) VALUES (?,?)"  # for 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 ()

#查询记录
select_sql = "SELECT * FROM Staff"
Cur.execute (select_sql)

#返回一个list, the object type in the list is tuple (tuple)
date_set = Cur.fetchall () for
row in Date_set:
  print (Row)

cur.close ()
con.close ()

I hope this example will help you with your Python learning.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.