跳至主要内容

python 之 SQLite

http://python101.pythonlibrary.org/chapter18_sqlite.html

SQLite是一个独立的,无服务器的,无配置的事务型SQL数据库引擎
SQLite仅支持五种数据类型:null, integer, real, text and blob

import sqlite3

conn = sqlite3.connect("mydatabase.db") # or use :memory: to put it in RAM

cursor = conn.cursor()

# create a table
cursor.execute("""CREATE TABLE albums
                  (title text, artist text, release_date text,
                   publisher text, media_type text)
               """)

# insert some data
cursor.execute("""INSERT INTO albums
                  VALUES ('Glow', 'Andy Hunter', '7/24/2012',
                          'Xplore Records', 'MP3')"""
               )

# save data to database
conn.commit()
------------------------------------------
# insert multiple records using the more secure "?" method
albums = [('Exodus', 'Andy Hunter', '7/9/2002', 'Sparrow Records', 'CD'),
          ('Until We Have Faces', 'Red', '2/1/2011', 'Essential Records', 'CD'),
          ('The End is Where We Begin', 'Thousand Foot Krutch', '4/17/2012', 'TFKmusic', 'CD'),
          ('The Good Life', 'Trip Lee', '4/10/2012', 'Reach Records', 'CD')]
cursor.executemany("INSERT INTO albums VALUES (?,?,?,?,?)", albums)
conn.commit()

---------------------------------------
import sqlite3

conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()

sql = """
UPDATE albums
SET artist = 'John Doe'
WHERE artist = 'Andy Hunter'
"""
cursor.execute(sql)
conn.commit()


---------------------------------------
import sqlite3

conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()

sql = """
DELETE FROM albums
WHERE artist = 'John Doe'
"""
cursor.execute(sql)
conn.commit()


--------------------------------
import sqlite3

conn = sqlite3.connect("mydatabase.db")
#conn.row_factory = sqlite3.Row
cursor = conn.cursor()

sql = "SELECT * FROM albums WHERE artist=?"
cursor.execute(sql, [("Red")])
print(cursor.fetchall())  # or use fetchone()

print("\nHere's a listing of all the records in the table:\n")
for row in cursor.execute("SELECT rowid, * FROM albums ORDER BY artist"):
    print(row)

print("\nResults from a LIKE query:\n")
sql = """
SELECT * FROM albums
WHERE title LIKE 'The%'"""
cursor.execute(sql)
print(cursor.fetchall())

我们执行SQL并使用fetchall()返回所有结果。您也可以使用fetchone()获取第一个结果。您还将注意到,其中有一个与神秘的row_factory相关的注释掉的部分。如果您取消注释该行,则结果将作为类似于Python字典的Row对象返回,使您可以像字典一样访问该行的字段。但是,您不能使用Row对象进行项目分配


--------------------------------------------------


SQLAlchemy

https://www.sqlalchemy.org/
http://zetcode.com/db/sqlalchemy/intro/
https://www.pythoncentral.io/introductory-tutorial-python-sqlalchemy/

SQLAlchemy是Python SQL工具箱和对象关系映射器,它为应用程序开发人员提供了SQL的全部功能和灵活性。
它提供了一整套众所周知的企业级持久性模式,旨在用于高效和高性能的数据库访问,并被适配为简单的Pythonic域语言




pip install sqlalchemy

# Create a Database
# table_def.py
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref

engine = create_engine('sqlite:///mymusic.db', echo=True)
Base = declarative_base()

class Artist(Base):
    """"""
    __tablename__ = "artists"

    id = Column(Integer, primary_key=True)
    name = Column(String)

class Album(Base):
    """"""
    __tablename__ = "albums"

    id = Column(Integer, primary_key=True)
    title = Column(String)
    release_date = Column(Date)
    publisher = Column(String)
    media_type = Column(String)

    artist_id = Column(Integer, ForeignKey("artists.id"))
    artist = relationship("Artist", backref=backref("albums", order_by=id))

# create tables
Base.metadata.create_all(engine)




# Insert / Add Data to Your Tables
# add_data.py
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from table_def import Album, Artist

engine = create_engine('sqlite:///mymusic.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)
session = Session()

# Create an artist
new_artist = Artist(name="Newsboys")

new_artist.albums = [Album(title="Read All About It",
                           release_date=datetime.date(1988,12,1),
                           publisher="Refuge", media_type="CD")]

# add more albums
more_albums = [Album(title="Hell Is for Wimps",
                     release_date=datetime.date(1990,7,31),
                     publisher="Star Song", media_type="CD"),
               Album(title="Love Liberty Disco",
                     release_date=datetime.date(1999,11,16),
                     publisher="Sparrow", media_type="CD"),
               Album(title="Thrive",
                     release_date=datetime.date(2002,3,26),
                     publisher="Sparrow", media_type="CD")]
new_artist.albums.extend(more_albums)

# Add the record to the session object
session.add(new_artist)
# commit the record the database
session.commit()

# Add several artists
session.add_all([
    Artist(name="MXPX"),
    Artist(name="Kutless"),
    Artist(name="Thousand Foot Krutch")
    ])
session.commit()





# Modify Records with SQLAlchemy
# modify_data.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from table_def import Album, Artist

engine = create_engine('sqlite:///mymusic.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)
session = Session()

# querying for a record in the Artist table
res = session.query(Artist).filter(Artist.name=="Kutless").first()
print(res.name)

# changing the name
res.name = "Beach Boys"
session.commit()

# editing Album data
artist, album = session.query(Artist, Album).filter(
    Artist.id==Album.artist_id).filter(Album.title=="Thrive").first()
album.title = "Step Up to the Microphone"
session.commit()





# Delete Records in SQLAlchemy
# deleting_data.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from table_def import Album, Artist

engine = create_engine('sqlite:///mymusic.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)
session = Session()

res = session.query(Artist).filter(Artist.name=="MXPX").first()

session.delete(res)
session.commit()




# The Basic SQL Queries of SQLAlchemy
# queries.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from table_def import Album, Artist

engine = create_engine('sqlite:///mymusic.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)
session = Session()

# how to do a SELECT * (i.e. all)
res = session.query(Artist).all()
for artist in res:
    print(artist.name)

# how to SELECT the first result
res = session.query(Artist).filter(Artist.name=="Newsboys").first()

# how to sort the results (ORDER_BY)
res = session.query(Album).order_by(Album.title).all()
for album in res:
    print(album.title)

# how to do a JOINed query
qry = session.query(Artist, Album)
qry = qry.filter(Artist.id==Album.artist_id)
artist, album = qry.filter(Album.title=="Step Up to the Microphone").first()

# how to use LIKE in a query
res = session.query(Album).filter(Album.publisher.like("S%a%")).all()
for item in res:
    print(item.publisher)





















评论

此博客中的热门博文

Chrome浏览器

谷歌搜索 双引号——精确搜索 冒号后加文件类型——搜索特定类型的结果 关键词 后 site:**——搜索特定网站的关键词 +、-关键词——实现特定需求筛选 Google中/——快捷键入浏览·搜索框 关键词后..——搜索特定范围(地点)关键词 intitle:关键词——搜索特定标题 用 puppeteer 直接运行 chrome 爬 https://github.com/puppeteer/puppeteer Puppeteer 是一个 Node 库,它提供了一个高级 API 来通过 DevTools 协议 控制 Chrome 或 Chromium 。Puppeteer默认 无头 运行,但可以配置为运行完整(非无头)Chrome 或 Chromium。 了解如何为 Chrome 开发扩展程序 https://developer.chrome.com/docs/extensions/mv3/ 什么是Chrome插件 https://github.com/sxei/chrome-plugin-demo Google Workspace 状态信息中心 https://www.google.com/appsstatus#hl=zh&v=status 此页面提供属于“Google Workspace”的服务的状态信息 谷歌浏览器离线下载 https://support.google.com/chrome/answer/95346?co=GENIE.Platform%3DDesktop&hl=zh-Hans 企业版 https://cloud.google.com/chrome-enterprise/browser/download 也可以在谷歌浏览器 帮助中心 中搜索chrome https://www.google.com/intl/zh-CN/chrome/?standalone=1 chrome 打开新网页时不要覆盖 鼠标 中键(滚轮)点击超链接 ,或者右击超链接,选择新标签页打开, 还有点链接的同时按下 Ctrl 键也可以 谷歌在线翻译网页 http://translate.google.com/translate?u= http://www.dropitproject.com/index.php 打开chrome浏览器按 F6 ,等同于按 ...

python 之 configparser、configobj(ini配置文件)

ini 即 Initialize 初始化之意,通常由节(Section)、键(key)和值(value)组成 ini修改工具 https://visionlore.com/lab/ini_editor.php https://www.horstmuc.de/wbat32.htm#inifile 语法      INIFILE filename.ini [section] item=string # db.ini 中的内容 # ********************* # [localdb] # host     = 127.0.0.1 # user     = root # password = 123456 # port     = 3306 # database = mysql # *********************   import pymysql from configparser import ConfigParser   cfg = ConfigParser ( ) cfg. read ( "db.ini" )   print ( cfg. items ( "localdb" ) ) db_cfg = dict ( cfg. items ( "localdb" ) ) print ( db_cfg )   # 端口port类型str转为int db_cfg [ 'port' ] = int ( db_cfg [ 'port' ] ) con = pymysql. connect ( **db_cfg )   from pprint import pprint lst = [ line. strip ( ) for line in open ( 'db.ini' ) ] pprint ( lst ) http://www.voidspace.org.uk/python/articles/configobj.shtml https://configobj.readthedocs.io/en/latest/configobj.html https://pythonhosted.or...

tkinter 入门

查看tkinter版本 方法一: cmd直接输入 python -m tkinter 方法二: cmd输入python >>> import tkinter >>> tkinter._test() >>> tkinter.Tcl().eval('info patchlevel') 参考资料 https://www.geeksforgeeks.org/python-gui-tkinter/ https://likegeeks.com/python-gui-examples-tkinter-tutorial/ http://www.openbookproject.net/courses/python4fun/tkphone1.html tkinter框架 #导入(调用)tkinter模块 from tkinter import * #创建Tk()的对象,它实际上用于创建窗口 my_window = Tk() #调用mainloop()函数,用于窗口的无限循环。当我们点击关闭按钮或退出应用程序时,mainloop()函数终止 my_window.mainloop() print( id(my_window), type(my_window),dir(my_window) ) 输出 53949680 <class 'tkinter.Tk'> ['_Misc__winfo_getint', '_Misc__winfo_parseitem', '__class__',...] #遍历 for key in root.keys():     print(key,":",root[key]) 设置窗口标题 my_window.title("Demo") 更改左上角图标 my_window.iconbitmap(r'C:\src\dragon-face.ico') from pathlib import Path my_window.iconbitmap(Path('img/dr...