How to work with sqlite3 and Python

前端 未结 4 559
刺人心
刺人心 2021-01-20 21:50

I was looking for any database solution with Python. And found the tutorial Python: A Simple Step-by-Step SQLite Tutorial. There I found a code example which shows how to cr

4条回答
  •  旧巷少年郎
    2021-01-20 22:33

    Sqlite3 is the version commonly used with Python. If you are running Windows, you need to download sqlite download from official page. If you are using Ubuntu or Debian based system then it comes pre-installed.

    Now coming to python, sqlite3 is the package name, it comes included with python, if you don't find it, then install it with the command apt-get install python-sqlite on Ubuntu system.

    Considering you are using Ubuntu system, simply type sqlite3 test.db to create database name test.db.

    As for your program:

    import sqlite3 
    
    conn = sqlite3.connect("test.db") # connect to test.db 
    cursor = conn.cursor() # get a cursor to the sqlite database 
    # cursor is the object here, you can use any name
    
    # create a table
    cursor.execute("""CREATE TABLE albums
                      (title text, artist text, release_date text, 
                       publisher text, media_type text)""")
    # cursor.execute is used to execute any command to sqlite
    

    Few more function I would like to introduce is data = cursor.fetchone() to fetch one row, data = cursor.fetchall() to fetch many rows at once and store in tuple data.

提交回复
热议问题