python之SQLite笔记

sqlite3

打开文件并创建游标

conn = sqlite3.connect('adressbook.db')
c = conn.cursor()

      连接对象:sqlite3.connect('数据文件.db') : commit() 在sqlite3中会看到操作的结果

                                                                        close()关闭连接,下次操作数据时需再连接

      建立任务让游标来执行

      游标:cursor = conn.cursor(): execute('SQL语句',[参数])

                                 fetchall():获取所有结果到列表

                                fetchone():获取一个结果到列表

                                fetchmany(记录数):获取自己想要个数的结果到列表

参数化查询:避免SQL注入: ? :参数传递tuple

                                :参数名,参数传递dict

      例如:

     避免这样做

    name = 'Tom'

    sql = "select * from LinkMan where Name='{}'".format(name)

    c.execute(sql)   # 这里的为游标

   可以这样做

    name = ('Tom',)

   sql = "select * from LinkMan where Name= ?"

   c.execute(sql, name) 

   

    还可以这样做 

    sql = "insert into LinkMan values (:name,:mobile,:birthdate,:isvalid)"

    c.execute(sql,{"name":"John","mobile":"18922210000","birthdate":"1989-12-11","isvalid":1})

原文地址:https://www.cnblogs.com/yang901112/p/11355082.html