Django & SQLite All In One

xgqfrms發表於2024-04-15

Django & SQLite All In One

Python & database

# python 3.11 & django 5.0.4
$ python manage.py migrate

image

$ cd django_website

$ ls -al
total 264
drwxr-xr-x   7 xgqfrms-mm  staff     224 Apr 15 02:09 .
drwxr-xr-x@ 11 xgqfrms-mm  staff     352 Apr 12 16:03 ..
-rw-r--r--   1 xgqfrms-mm  staff  131072 Apr 15 02:09 db.sqlite3
drwxr-xr-x  11 xgqfrms-mm  staff     352 Apr 14 00:27 django_app
drwxr-xr-x   8 xgqfrms-mm  staff     256 Apr 13 23:06 django_website
-rwxr-xr-x   1 xgqfrms-mm  staff     770 Apr 13 23:30 manage.py
drwxr-xr-x  11 xgqfrms-mm  staff     352 Apr 14 00:34 polls

# sqlite3 database_name ✅
$ sqlite3 db.sqlite3
SQLite version 3.43.2 2023-10-10 13:08:14
Enter ".help" for usage hints.
# .tables ✅
sqlite> .tables
auth_group                  auth_user_user_permissions
auth_group_permissions      django_admin_log          
auth_permission             django_content_type       
auth_user                   django_migrations         
auth_user_groups            django_session           
# .exit ✅
sqlite> .exit

image

SQLite

CLI / Command Line Shell For SQLite

https://sqlite.org/cli.html

$ which sqlite3
# /usr/bin/sqlite3

# SQLite  3.43.2
$ sqlite3
SQLite version 3.43.2 2023-10-10 13:08:14
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
# help
sqlite> .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection [close] [#]  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.hex-rekey OLD NEW NEW   Change the encryption key using hexadecimal
.import FILE TABLE       Import data from FILE into TABLE
.import FILE TABLE       Import data from FILE into TABLE
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.log FILE|on|off         Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?OPTIONS?     Set output mode
.nonce STRING            Suspend safe mode for one command if nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Stop interpreting input stream, exit if primary.
.read FILE               Read input from FILE or command output
.recover                 Recover as much data as possible from corrupt db.
.rekey OLD NEW NEW     Change the encryption key
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save ?OPTIONS? FILE     Write database to FILE (an alias for .backup ...)
.scanstats on|off|est    Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.text-rekey OLD NEW NEW  Change the encryption key using hexadecimal
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.version                 Show source, library and compiler versions
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output
sqlite> 
# exit
sqlite> .exit
# create a new SQLite database named "db1" with a single table named "tb1", you might do this:
$ sqlite3 db1
SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
sqlite> create table tb1(one text, two int);
sqlite> insert into tb1 values('hello!',10);
sqlite> insert into tb1 values('goodbye', 20);
sqlite> select * from tb1;
hello!|10
goodbye|20
sqlite>

The sqlite3 program looks for a semicolon to know when your SQL command is complete.

sqlite> CREATE TABLE tb2 (
   ...>   f1 varchar(30) primary key,
   ...>   f2 text,
   ...>   f3 real
   ...> );
sqlite>

SQLite 教程

https://www.runoob.com/sqlite/sqlite-tutorial.html

# https://www.sqlite.org/download.html
$ tar xvzf sqlite-autoconf-3071502.tar.gz

$ cd sqlite-autoconf-3071502

$ ./configure --prefix=/usr/local

$ make

$ make install

https://www.runoob.com/sqlite/sqlite-installation.html

demos

django models

from django.db import models


class Band(models.Model):
    """A model of a rock band."""

    name = models.CharField(max_length=200)
    can_rock = models.BooleanField(default=True)


class Member(models.Model):
    """A model of a rock band member."""

    name = models.CharField("Member's name", max_length=200)
    instrument = models.CharField(
        choices=(
            ("g", "Guitar"),
            ("b", "Bass"),
            ("d", "Drums"),
        ),
        max_length=1,
    )
    band = models.ForeignKey("Band")

https://docs.djangoproject.com/en/stable/topics/db/models/

(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個資訊, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 檢視原創文章!

refs

https://docs.djangoproject.com/en/5.0/intro/tutorial02/

https://www.djangoproject.com/start/



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 釋出文章使用:只允許註冊使用者才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!


相關文章