• python3连接使用sqlite3


    一直比较喜欢sqlite,业余爱好不需要大型数据库,原来在windows下最常用的就是access,使用很方便,但是linux下没法用,后 来从php+sqlite2开始使用,编程时间很少,代码量很小所以不是很熟悉。现在又开始学python(汗一个先,我都不知道这是第几次开始 了,^_^,没怎么能坚持,所以依然还是学基础),首选sqlite3.

    在python中连接使用sqlite3非常方便,需要载入sqlite3模块就能使用了

     1 import sqlite3
     2 #建立连接
     3 conn = sqlite3.connect('/tmp/example')
     4 
     5 #建立了连接之后可以使用Cursor对象和execute方法执行sql命令
     6 c = conn.cursor()
     7 c.execute("""insert into user values ('3','qq','1234')""")
     8 conn.commit()
     9 rec = c.execute("""select * from user""")
    10 print(c.fetchall())

    python3对sqlite3的操作就依赖sqlite3模块,改模块的功能和常量有:

    PARSE_DECLTYPES 

    PARSE_COLNAMES

    connect(database, [timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])
    register_converter(typename, callable)
    register_adapter(type, callable)
    complete_statement(sql)
    enable_callback_tracebacks(flag)
     
    另一个demo
    #!/depot/Python-2.5/bin/python
    import sqlite3
    
    #链接数据库文件
    #如果数据库文件不存在,回新建一个,如果存在则打开此文件
    conn = sqlite3.connect('example')
    c = conn.cursor()
    
    #创建表格
    c.execute('''create table stocks (date text, trans text, symbol text,  qty real, price real)''')
    
    # 插入数据,执行SQL语句
    c.execute("""insert into stocks values ('2006-01-15','BUoY','RHATd',100,35.14)""")
    
    #将变动保存到数据库文件,如果没有执行词语句,则前面的insert 语句操作不会被保存
    conn.commit()
    
    #得到所有的记录
    rec = c.execute('''select * from stocks''')
    print c.fetchall()
  • 相关阅读:
    面向对象实验 ——(二)类与对象
    [LeetCode] 957. Prison Cells After N Days
    [LeetCode] 32. Longest Valid Parentheses
    [LeetCode] 120. Triangle
    [LeetCode] 441. Arranging Coins
    [LeetCode] 79. Word Search
    [LeetCode] 1143. Longest Common Subsequence
    [LeetCode] 718. Maximum Length of Repeated Subarray
    [LeetCode] 332. Reconstruct Itinerary
    [LeetCode] 279. Perfect Squares
  • 原文地址:https://www.cnblogs.com/mmix2009/p/3225489.html
Copyright © 2020-2023  润新知