Answers for "how to connect to sqlite3 database in python"

SQL
5

python sqlite3 database

import sqlite3

# Create database
conn = sqlite3.connect('tablename.db')
c = conn.cursor()
c.execute('''CREATE TABLE tablename(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, number REAL)''')
conn.commit()
conn.close()

# Insert Values
conn = sqlite3.connect('tablename.db')
c = conn.cursor()
c.execute("INSERT INTO tablename VALUES (?, ?)", (name, number))
conn.commit()
conn.close()

# Read Values
conn = sqlite3.connect('tablename.db')
c = conn.cursor()

for row in c.execute('SELECT * FROM tablename'):
	print(row)

number = [row[2] for row in c.execute('SELECT * FROM tablename')]
conn.close()
Posted by: Guest on June-27-2021
2

sqlite python connection

import sqlite3

try:
    sqliteConnection = sqlite3.connect('SQLite_Python.db')
    cursor = sqliteConnection.cursor()
    print("Database created and Successfully Connected to SQLite")

    sqlite_select_Query = "select sqlite_version();"
    cursor.execute(sqlite_select_Query)
    record = cursor.fetchall()
    print("SQLite Database Version is: ", record)
    cursor.close()

except sqlite3.Error as error:
    print("Error while connecting to sqlite", error)
finally:
    if (sqliteConnection):
        sqliteConnection.close()
        print("The SQLite connection is closed")
Posted by: Guest on July-27-2020
2

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()
Posted by: Guest on February-07-2021

Code answers related to "how to connect to sqlite3 database in python"

Code answers related to "SQL"

Browse Popular Code Answers by Language