Python - SQLite

SQLite3 Site


Sqlite3 Client


Python 에서 Sqlite 사용


Step 0: Create Table


CREATE TABLE `miniboard` ( 
`idx` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 
`writer` TEXT NOT NULL, 
`title` TEXT NOT NULL, 
`content` TEXT NOT NULL, 
`regdate` TEXT NOT NULL DEFAULT (datetime('now','localtime'))
)

or

새로 만들거나 있으면 연결

conn = sqlite3.connect('./data/python.db')

table = ''' CREATE TABLE miniboard2 ( idx INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, writer TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL, regdate TEXT NOT NULL DEFAULT (datetime('now','localtime')) ) ''' with conn: cursor = conn.cursor() cursor.execute(table) cursor.close() ``

Python에서 SQLite사용하는 일반적인 절차


Step 1: Connect


import sqlite3
connection = sqlite3.connect('python.db')`

Step 2: Execute query


import sqlite3
connection = sqlite3.connect('python.db')

with connection:
    cursor = connection.cursor()
    sql = "select * from miniboard order by idx desc "
    #sql = "select * from miniboard where idx = ? order by idx desc",(3,)"

    cursor.execute(sql)
    #cursor.execute(sql, ('1',))

    rows = cursor.fetchone()
    print(rows)
import sqlite3

connection = sqlite3.connect('python.db')

with connection:
    cursor = connection.cursor()
    sql = "select * from `miniboard` order by idx desc "
    cursor.execute(sql)
    rows = cursor.fetchall()
    for row in rows:
        print(row)

Step 3: Insert a row


import sqlite3
connection = sqlite3.connect('python.db')

with connection:
    cursor = connection.cursor()
    sql = "INSERT INTO `miniboard` (`writer`, `title`, `content`) VALUES (?, ?, ?)"
    cursor.execute(sql, ('mooni', 'mooni title', 'mooni content'))

    connection.commit()

with connection:
    cursor = connection.cursor()
    sql = "SELECT * FROM `miniboard` WHERE `writer`= ?"
    cursor.execute(sql, ('mooni',))
    rows = cursor.fetchone()
    print(rows)