tables projects tasks Code language: CSS ( css )Īs you can see clearly from the output, we are having the projects and tasks tables in the pythonsqlite.db database. tables command to display the tables in the database. Let’s verify if the program has created those tables successfully in the pythonsqlite.db database.įirst, launch the command line and connect to the pythonsqlite.db database: >sqlite3 c:\sqlite\db\pythonsqlite.db Main() Code language: SQL (Structured Query Language) ( sql )ĭef create_connection (db_file): """ create a database connection to the SQLite databaseĭef create_table (conn, create_table_sql): """ create a table from the create_table_sql statement Print( "Error! cannot create the database connection.")įourth, execute the main() function. Sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks (įOREIGN KEY (project_id) REFERENCES projects (id)Ĭreate_table(conn, sql_create_projects_table)Ĭreate_table(conn, sql_create_tasks_table) Sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS projects ( def main ():ĭatabase = r"C:\sqlite\db\pythonsqlite.db" Third, create a main() function to create the projects and tasks tables. Print(e) Code language: SQL (Structured Query Language) ( sql ) :param create_table_sql: a CREATE TABLE statement """ create a table from the create_table_sql statement def create_table(conn, create_table_sql): Inside the function, we call the execute() method of the Cursor object to execute the CREATE TABLE statement. Second, develop a function named create_table() that accepts a Connection object and an SQL statement. Return conn Code language: Python ( python ) def create_connection (db_file): """ create a database connection to the SQLite database Let’s see how to create new tables in Python.įirst, develop a function called create_connection() that returns a Connection object which represents an SQLite database specified by the database file parameter db_file. ) Code language: SQL (Structured Query Language) ( sql ) tasks table CREATE TABLE IF NOT EXISTS tasks (įOREIGN KEY (project_id) REFERENCES projects ( id) The following CREATE TABLE statements create these two tables: - projects table CREATE TABLE IF NOT EXISTS projects ( Third, pass the CREATE TABLE statement to the execute() method of the Cursor object and execute this method.įor the demonstration, we will create two tables: projects and tasks as shown in the following database diagram:.Second, create a Cursor object by calling the cursor() method of the Connection object. First, create a Connection object using the connect() function of the sqlite3 module.To create a new table in an SQLite database from a Python program, you use the following steps: Summary: in this tutorial, we will show you how to create tables in the SQLite database from the Python program using the sqlite3 module.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |