Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the built-in database in python?

Shulou Source: shulou.com Published: 2022-06-02 21:51:46 09月14日 Update

This article mainly introduces "what is python's built-in database". In daily operation, I believe many people have doubts about what python's built-in database is. Xiaobian consulted all kinds of information and sorted out simple and easy to use operation methods. I hope to help you answer the question of "what is python's built-in database"! Next, please follow the small series to learn together!

Input and use

When we say "built-in," it means you don't even have to run pip install to get the library. Simply import by:

import sqlite3 as sl

Create a connection to the database

Don't fret about drivers, connection strings, etc. You can create a SQLite database with a simple connection object:

con = sl.connect('my-test.db')

After running this line of code, we have created the database and connected to it. We ask Python to automatically join existing databases, so it's not empty. Otherwise, we can connect to an existing database using exactly the same code.

create tables

Then create a table:

with con: con.execute(""" CREATE TABLE USER ( id INTEGER NOT NULL PRIMARYKEY AUTOINCREMENT, name TEXT, age INTEGER ); """)

Add three columns to this user table. As you can see, SQLite is indeed lightweight, but it supports all the basic features that a regular RDBMS should have, such as data types, nullability, primary keys, and auto-increment. Running this code creates a table, although it outputs nothing.

insert records

Let's insert some records into the USER table we just created, which also proves that we did create it. Suppose you want to insert multiple entries at once. SQLite in Python makes this easy.

sql = 'INSERT INTO USER (id, name, age) values(?,?, ?) ' data = [ (1, 'Alice', 21), (2, 'Bob', 22), (3, 'Chris', 23) ]

We need to define SQL statements with question marks as placeholders. Then, create some sample data to insert. Insert these sample rows by connecting objects.

with con: con.executemany(sql, data)

After running the code, there is no hint that we succeeded.

lookup table

Now, it's time to test everything. Query the table for sample rows.

with con: data = con.execute("SELECT *FROM USER WHERE age

Tags: Data database run code customer learning file seamless query client client object general method more query table feature example type result Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information macOS Shulou Tech Info Xiaomi NVidia