Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python sqlite

import sqlite3
import os.path

#Connection to the DB
try:
    # Make sure to find the file.db in the script directory
    BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 
    db_path = os.path.join(BASE_DIR, "sqlite.db")
    conn = sqlite3.connect(db_path)

except sqlite3.Error as error:
    print("Failed to read data from sqlite table", error)



# Execute query on the sqlite DB
cur = conn.cursor()
cur.execute("SELECT * FROM tasks")

# Print everything from a table
rows = cur.fetchall()
for row in rows:
        print(row)
    
# Update field 
conn.execute("""UPDATE tasks SET name = 'jhon'
 where id = 1""")

# close the DB connection 
conn.close() 
Comment

sqlite3 python

import sqlite3 as lite 
import sys 
 
try: 
    con = lite.connect('products.db') 
    cur = con.cursor()     
    cur.execute("CREATE TABLE drinks(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Price REAL)") 
    cur.execute("CREATE TABLE fruits(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Price REAL)") 
    con.commit() 
             
except e: 
    if con: 
        con.rollback() 
     
    print("Unexpected error %s:" % e.args[0]) 
    sys.exit(1) 
finally: 
    if con: 
        con.close()  
Comment

python sqlite

import sqlite3

con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()

buffer = ""

print("Enter your SQL commands to execute in sqlite3.")
print("Enter a blank line to exit.")

while True:
    line = input()
    if line == "":
        break
    buffer += line
    if sqlite3.complete_statement(buffer):
        try:
            buffer = buffer.strip()
            cur.execute(buffer)

            if buffer.lstrip().upper().startswith("SELECT"):
                print(cur.fetchall())
        except sqlite3.Error as e:
            print("An error occurred:", e.args[0])
        buffer = ""

con.close()
Comment

sqlite3 python

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_project(conn, project):
    """
    Create a new project into the projects table
    :param conn:
    :param project:
    :return: project id
    """
    sql = ''' INSERT INTO projects(name,begin_date,end_date)
              VALUES(?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, project)
    conn.commit()
    return cur.lastrowid


def create_task(conn, task):
    """
    Create a new task
    :param conn:
    :param task:
    :return:
    """

    sql = ''' INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date)
              VALUES(?,?,?,?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, task)
    conn.commit()
    return cur.lastrowid


def main():
    database = r"C:sqlitedbpythonsqlite.db"

    # create a database connection
    conn = create_connection(database)
    with conn:
        # create a new project
        project = ('Cool App with SQLite & Python', '2015-01-01', '2015-01-30');
        project_id = create_project(conn, project)

        # tasks
        task_1 = ('Analyze the requirements of the app', 1, 1, project_id, '2015-01-01', '2015-01-02')
        task_2 = ('Confirm with user about the top requirements', 1, 1, project_id, '2015-01-03', '2015-01-05')

        # create tasks
        create_task(conn, task_1)
        create_task(conn, task_2)


if __name__ == '__main__':
    main()
Code language: Python (python)
Comment

PREVIOUS NEXT
Code Example
Python :: compress tarfile python 
Python :: concatenate 2 array numpy 
Python :: application/x-www-form-urlencoded python 
Python :: python file reading 
Python :: create a python3 virtual environment 
Python :: python requests response get text 
Python :: python pop element 
Python :: python check if int 
Python :: python get average of list 
Python :: python tkinter fenstergröße 
Python :: spacy config 
Python :: sha512 python 
Python :: delete nans in df python 
Python :: python __init_subclass__ 
Python :: turn df to dict 
Python :: concat dataframes 
Python :: python count bits 
Python :: decimal in python 
Python :: append vs insert python 
Python :: output path jupyter 
Python :: Add Border to input Pysimplegui 
Python :: dataframe create 
Python :: discord.py say something 
Python :: press key on python 
Python :: remove all odd row pandas 
Python :: Python Requests Library Post Method 
Python :: operator precedence in python 
Python :: how to connect an ml model to a web application 
Python :: how to delete a variable python 
Python :: how to create a matrix using python 
ADD CONTENT
Topic
Content
Source link
Name
9+1 =