python資料庫的增刪改查

2022-09-17 19:18:11 字數 1592 閱讀 2117

#coding=utf-8

from

sqlalchemy import create_engine

from

sqlalchemy.orm import sessionmaker

from

sqlalchemy import column

from

sqlalchemy.types import char, integer, string

from

sqlalchemy.ext.declarative import declarative_base

base=declarative_base()

class

product(base):

__tablename__='

product

'id = column(string(20), primary_key=true) # 字段

name = column(string(20

)) # 字段

type= column(string(20

)) # 字段

engine = create_engine('

mssql+pymssql://sa:root@localhost:1433/world

')#初始化資料庫連線

dbsession=sessionmaker(bind=engine)#建立dbsesson型別

base.metadata.create_all(engine)#建立表結構

#向資料庫寫入

session=dbsession()#建立session物件

new_user=product(id='

1233445

',name='

寧夏一日遊

',type='

景+酒'

)#建立新product物件

session.add(new_user)#新增到session

session.commit()#提交即儲存到資料庫

#查詢#建立query查詢。filter是where條件,最後呼叫one()返回唯一行,如果呼叫all()則返回所有行

student=session.query(product).filter(product.id=='

1233445

').one()

#列印物件的name,class_name屬性

print(

'name:

',student.name)

print(

'class_name:

',student.type)

#查詢並更新資料

session.query(product).filter(product.id=='

1233445

').update()

session.commit()

#查詢並刪除資料

session.query(product).filter(product.id='

1233445

').delete()

session.commit()

session.close()

資料庫增刪改查

我們知道當我們的表建立後重複執行會出錯,一般我們會這麼處理 create table if not exists stuinfo 學了新建表我們還應該知道乙個東西,如何刪除表 deop table table name 怎麼檢視別人的見表語句呢 show create table stuinfo 怎...

資料庫增刪改查

import pymysql def getmysqlconn conn pymysql.connect host 172.16.238.130 port 3306,db my mysql user root password 123456 charset utf8 return conn def ...

資料庫增刪改查

資料庫操作 show databases create database 資料庫名 use 資料庫名 select database drop database 資料庫名 資料表操作 create table 表名 欄位名 型別名 約束 show tables drop table 表名 資料表增刪...