python link sqlite database problem

One, create a database

Code to create sqlite database

import sqlite3
conn = sqlite3.connect("test.db")
print("成功创建数据库")

After running the code, the "test.db" file will appear in the file column on the left,
Insert picture description here

Two, link to the database

View->Tool Window->Database
Insert picture description here

At this time Database appears on the right side of the editor, click the Add buttonInsert picture description here

Click the path selection button, find the created "test.db" file, select it.
Insert picture description here
Insert picture description here
Note: When downloading, you may be prompted that the download failed. If you try two more times, it will always download.
At this point, the database is linked.

Third, the addition, deletion and search of the database

1. Add header

c = conn.cursor()     #获取游标
sql = '''
    create table company
        (id int primary key not null,
        name text not null,
        age int not null,
        address char(50),
        salary real);
'''
c.execute(sql)      #执行sql语句
conn.commit()       #提交数据库操作
conn.close()        #关闭数据库链接
print("成功建表")

2. Insert data

conn = sqlite3.connect("test.db")
print("成功打开数据库")
c = conn.cursor()     #获取游标
sql1 = '''
    insert into company (id,name,age,address,salary)
     values (1,'张三',32,"成都",8000);

'''
sql2 = '''
    insert into company (id,name,age,address,salary)
     values (2,'李四',30,"深圳",15000);

'''
c.execute(sql1)     #执行sql语句
c.execute(sql2)
conn.commit()       #提交数据库操作
conn.close()        #关闭数据库链接
print("成功插入数据")

3. Find data

conn = sqlite3.connect("test.db")
print("成功打开数据库")
c = conn.cursor()  # 获取游标
sql = '''
   select id,name,address,salary from company
'''

cursor = c.execute(sql)  # 执行sql语句
for row in cursor:
    print("id = ",row[0])
    print("name = ",row[1])
    print("address = ",row[2])
    print("salary = ",row[3],"\n")

conn.close()  # 关闭数据库链接
print("成功查找数据")

Four, running results

Console print data
Insert picture description here
database table content
Insert picture description here

Guess you like

Origin blog.csdn.net/gets_s/article/details/112172061