美文网首页
python 存储数据到数据库

python 存储数据到数据库

作者: 温柔vs先生 | 来源:发表于2021-12-28 09:55 被阅读0次
    #!/usr/bin/env python
    # -*- encoding: utf-8 -*-
    '''
    @文件        :test_db.py
    @说明        :
    @时间        :2021/12/27 17:26:12
    @作者        :wbb
    @版本        :1.0
    '''
    
    import sqlite3
    
    from douban import initDB
    
    
    def main():
        dbPath = "test.db"
        initDB(dbPath)
        # insterData(dbPath)
        selectData(dbPath)
    
    # 查看数据
    def selectData(dbPath):
        conn = sqlite3.connect(dbPath)
        # 获取游标
        cur = conn.cursor()
        sql = '''
            select * from test
        '''
        cur.execute(sql)
    
        for row in cur:
            print("id =", row[0])
            print("name =", row[1])
            print("age =", row[2])
            print("address =", row[3], "\n")
    
    
    # 插入数据
    def insterData(dbPath):
        conn = sqlite3.connect(dbPath)
        # 获取游标
        cur = conn.cursor()
    
        sql = '''
            insert into test (name, age, address)
            values("张三", 18, "河南")
        '''
        cur.execute(sql)
        sql1 = '''
            insert into test (name, age, address)
            values("李四", 17, "重庆")
        '''
        cur.execute(sql1)
        # 提交表
        conn.commit()
        # 关闭表
        conn.close()
    
    
    # 初始化表
    def initDB(dbPath):
        conn = sqlite3.connect(dbPath)
        print('建表成功')
    
        # 获取游标
        cur = conn.cursor()
    
        sql = '''
            create table if not exists test (
                id integer primary key not null,
                name text,
                age integer,
                address text
            )
        '''
        # 执行sql语句
        cur.execute(sql)
        # 提交表
        conn.commit()
        # 关闭表
        conn.close()
    
        print('成功建表')
    
    
    if __name__ == "__main__":
        main()
    
    

    相关文章

      网友评论

          本文标题:python 存储数据到数据库

          本文链接:https://www.haomeiwen.com/subject/jcfpqrtx.html