python sqllite basic operation

Here are some basic SQLite3 operations:

Connect to the database: Use the sqlite3.connect() function to connect to the database and return a Connection object through which we interact with the database. For example:

import sqlite3
conn = sqlite3.connect('example.db')

Create a table: Use the CREATE TABLE statement to create a table. For example:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')

Insert data: use the INSERT INTO statement to insert data. For example:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

Query data: Use the SELECT statement to query data. For example:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM stocks WHERE symbol="RHAT"'):
  print(row)

Update data: Use the UPDATE statement to update data. For example

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("UPDATE stocks SET price=25.00 WHERE symbol='RHAT'")
conn.commit()

Delete data: Use the DELETE FROM statement to delete data. For example:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("DELETE FROM stocks WHERE symbol='RHAT'")
conn.commit()

Guess you like

Origin blog.csdn.net/qq_16792139/article/details/132056547