分类
使用笔记

python sqlite3 插入数据

import sqlite3
from sqlite3 import Error


def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except Error as e:
        print(e)

    return conn


def create_task(conn, task):
    """
    Create a new task
    :param conn:
    :param task:
    :return:
    """
    sql = ''' INSERT INTO main_post(title,content,category,created_on,tag,post_status)
              VALUES(?,?,?,?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, task)
    conn.commit()

    return cur.lastrowid


database = r"Desktop\django-blog\blog\db.sqlite3"

conn = create_connection(database)


## 可以反复使用
id = create_task(conn, (x[1], x[2], category, x[4], html, 1))

参考SQLite Python: Inserting Data

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注