• Python 操作 SQLite



    一、导入sqlite数据库模块

        从Python2.5以后,sqlite3成为内置模块,不需要额外安装,只需要导入即可

               import sqlite3

    二、创建/打开数据库

            sqlite3模块中使用connect方法创建/打开数据库,需要指定数据库路径。若数据库存在则打开,不存在则创建一个新的数据库

               con = sqlite3.connect("/home/DataBases/user.db")

        不仅可以在硬盘上创建数据库文件,还可以在内存中创建

               con = sqlite3.connect(":memory:")

    三、数据库连接对象

           通过connect方法返回的con对象,就是数据库连接对象,它提供了以下方法:

                         cursor() : 创建游标对象

                         commit() : 提交事务

                        rollback() : 事务回滚

                         close(): 关闭数据库连接

    四、游标对象

               对数据库的查询需要使用游标对象,创建游标对象的方法是:

                        cur = con.cursor()

              游标对象有以下方法支持数据库的操作

                       execute():用来执行sql语句

                      executemany():用来执行多条sql语句

                       close():关闭游标

                      fetchone():用来从结果中取一条记录,并将游标指向下一条记录

                      fetchmany():从结果中取多条记录

                      fetchall():从结果中取出所有记录

                      scroll():游标回滚

    五、建表

                       cur.execute(‘create table person (id integer primary key,name varchar(20),age integer’)

    六、插入数据

             1、构造一个插入语句:容易导致SQL注入(不提倡)

                     data = "3,'王小五',25"

                     cur.execute('insert into person values (%s)'%data)

                     con.commit()

             2、使用站位符:?

                     cur.execute('insert into person values (?,?,?)',(4,'赵小六',22))

                     con.commit()

             3、一次插入多条记录

                     cur.executemany('insert into person values (?,?,?)',[(5,'赵小六',22),(6,'张消费',25),(7,'BBB',33)])

                     con.commit()

    七、修改数据

                    cur.execute('update person set name=? where id=?',('长孙无极',1))

                    con.commit()

    八、删除数据

                    cur.execute('delete from person where id=?',(2,))

                    con.commit()

    九、查询所有数据

                   cur.execute('select * from person')

                   res = cur.fetchall()

                   for line in res:

                            print(line)

  • 相关阅读:
    POJ 3419 Difference Is Beautiful (DP + 二分 + rmq)
    CodeForces 755C PolandBall and Forest (并查集)
    CodeForces 754D Fedor and coupons (优先队列)
    CodeForces 753C Interactive Bulls and Cows (Hard)
    CodeForces 754C Vladik and chat (DP+暴力)
    HDU 1996 汉诺塔VI (排列组合)
    HDU 1995 汉诺塔V (水题)
    HDU 2077 汉诺塔IV (递推)
    HDU 2064 汉诺塔III (递推)
    How Javascript works (Javascript工作原理) (二) 引擎,运行时,如何在 V8 引擎中书写最优代码的 5 条小技巧
  • 原文地址:https://www.cnblogs.com/lone5wolf/p/10909515.html
Copyright © 2020-2023  润新知