当前位置:   article > 正文

数据对象操作SQLAlchemy ----创建表_sqlalchemy column concat

sqlalchemy column concat
1. 创建表
  1. from sqlalchemy import MetaData
  2. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  3. from datetime import datetime
  4. from sqlalchemy import DateTime
  5. metadata=MetaData() #创建metadata对象
  6. cookies = Table('cookies', metadata,
  7. Column('cookie_id', Integer(), primary_key=True),
  8. Column('cookie_name', String(50), index=True),
  9. Column('cookie_recipe_url', String(255)),
  10. Column('cookie_sku', String(55)),
  11. Column('quantity', Integer()),
  12. Column('unit_cost', Numeric(12, 2))
  13. )
  14. users = Table('users', metadata,
  15. Column('user_id', Integer(), primary_key=True),
  16. Column('customer_number', Integer(), autoincrement=True),
  17. Column('username', String(15), nullable=False, unique=True),
  18. Column('email_address', String(255), nullable=False),
  19. Column('phone', String(20), nullable=False),
  20. Column('password', String(25), nullable=False),
  21. Column('created_on', DateTime(), default=datetime.now),
  22. Column('updated_on', DateTime(), default=datetime.now, onupdate=datetime.now)
  23. )
  24. orders=Table('orders',metadata,
  25. Column('order_id',Integer(),primary_key=True),
  26. Column('user_id',ForeignKey('users.user_id')) #外键user_id是ForeignKey(users.user_id的主键)
  27. )
  28. line_items = Table('line_items', metadata,
  29. Column('line_items_id', Integer(), primary_key=True),
  30. Column('order_id', ForeignKey('orders.order_id')),
  31. Column('cookie_id', ForeignKey('cookies.cookie_id')),
  32. Column('quantity', Integer()),
  33. Column('extended_cost', Numeric(12, 2))
  34. )
  35. engine=create_engine('mysql+mysqlconnector://root:root@localhost:3306/imooc') #连接数据库
  36. metadata.create_all(engine) #create_all创建全部的表

2. 插入/更新/删除等操作

插入数据有3种方法:insert

  1. from sqlalchemy import MetaData
  2. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  3. from datetime import datetime
  4. from sqlalchemy import DateTime
  5. metadata=MetaData()
  6. cookies = Table('cookies', metadata,
  7. Column('cookie_id', Integer(), primary_key=True),
  8. Column('cookie_name', String(50), index=True),
  9. Column('cookie_recipe_url', String(255)),
  10. Column('cookie_sku', String(55)),
  11. Column('quantity', Integer()),
  12. Column('unit_cost', Numeric(12, 2))
  13. )
  14. engine=create_engine('mysql://root:root@localhost/imooc')
  15. connection=engine.connect()
  16. #插入数据方法1==statement语法插入
  17. ins=cookies.insert().values(
  18. cookie_name="chocolate chip",
  19. cookie_recipe_url="http://some.aweso.me/cookie/recipe.html",
  20. cookie_sku="CC01",
  21. quantity="12",
  22. unit_cost="0.50"
  23. )
  24. print(str(ins)) #打印插入ins的值
  25. print ins.compile().params #compile()是以ins objeect对象返回
  26. #执行插入语句
  27. result = connection.execute(ins)
  28. #插入方法2:导入insert方法插入
  29. from sqlalchemy import insert
  30. ins = insert(cookies).values(
  31. cookie_name="dark chocolate chip",
  32. cookie_recipe_url="http://some.aweso.me/cookie/recipe_dark.html",
  33. cookie_sku="CC02",
  34. quantity="1",
  35. unit_cost="0.75"
  36. )
  37. result = connection.execute(ins)
  38. result.inserted_primary_key
  39. #插入方法3:values在执行语句中
  40. ins = cookies.insert()
  41. result = connection.execute(
  42. ins,
  43. cookie_name='kk chocolate chip',
  44. cookie_recipe_url='http://some.aweso.me/cookie/recipe_kk.html',
  45. cookie_sku='CC04',
  46. quantity='2',
  47. unit_cost='2.2'
  48. )
  49. result = connection.execute(ins)
  50. result.inserted_primary_key
  51. #批量插入
  52. ins = cookies.insert()
  53. inventory_list = [
  54. {
  55. 'cookie_name': 'peanut butter',
  56. 'cookie_recipe_url': 'http://some.aweso.me/cookie/peanut.html',
  57. 'cookie_sku': 'PB01',
  58. 'quantity': '24',
  59. 'unit_cost': '0.25'
  60. },
  61. {
  62. 'cookie_name': 'oatmeal raisin',
  63. 'cookie_recipe_url': 'http://some.okay.me/cookie/raisin.html',
  64. 'cookie_sku': 'EWW01',
  65. 'quantity': '100',
  66. 'unit_cost': '1.00'
  67. }
  68. ]
  69. result=connection.execute(ins,inventory_list) #ins是方法,inventory_list是批量插入的值

查询数据:select

  1. from sqlalchemy import MetaData
  2. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  3. metadata=MetaData()
  4. cookies = Table('cookies', metadata,
  5. Column('cookie_id', Integer(), primary_key=True),
  6. Column('cookie_name', String(50), index=True),
  7. Column('cookie_recipe_url', String(255)),
  8. Column('cookie_sku', String(55)),
  9. Column('quantity', Integer()),
  10. Column('unit_cost', Numeric(12, 2))
  11. )
  12. engine=create_engine('mysql://root:root@localhost/imooc')
  13. connection=engine.connect()
  14. #select取出所有数据
  15. from sqlalchemy.sql import select
  16. s = cookies.select()
  17. rp = connection.execute(s)
  18. results = rp.fetchall()
  19. print results
  20. first_row=results[0]
  21. #下面3条都取出cookie_name
  22. print first_row[1]
  23. print first_row.cookie_name
  24. print first_row[cookies.c.cookie_name]
  25. print "++++++++++++++++++++++++++++++++++++++++"
  26. #select取出部分字段数据
  27. s=select([cookies.c.cookie_name,cookies.c.cookie_sku,cookies.c.quantity])
  28. rp=connection.execute(s)
  29. results=rp.fetchall()
  30. print results
  31. print '++++++++++++++++++++++++++++++++++++++++'
  32. #返回的结果
  33. #[('chocolate chip', 'CC01', 12L), ('dark chocolate chip', 'CC02', 1L)]
  34. #取出每条信息
  35. # 它可以类似字典一样取出字段值:record.cookie_name,字段名就相当于key.取出所有值中字段名为cookie_name的值
  36. #而未导入sqlalchemy则,纯python元组是a[0]取数据,字典才会a["key"]取出值
  37. rp=connection.execute(s)
  38. for record in rp:
  39. print record #结果是元组:('chocolate chip', 'CC01', 12L)
  40. print (record.cookie_name)
  41. print '++++++++++++++++++++++++++++++++++++++++++'
  42. #查看字段名,取出第一条记录
  43. s=select([cookies.c.cookie_name,cookies.c.quantity])
  44. rp=connection.execute(s)
  45. print(rp.keys()) #rp.keys()是字段名 结果:['cookie_name', 'quantity']
  46. results=rp.first() #取出第一条记录
  47. print results

排序:order_by

限制返回记录条数:limit()

  1. #排序(升序)
  2. s=select([cookies.c.cookie_name,cookies.c.quantity])
  3. s=s.order_by(cookies.c.quantity)
  4. #或者合并成下面的一条语句
  5. # s=select([cookies.c.cookie_name,cookies.c.quantity]).order_by(cookies.c.quantity)
  6. #降序
  7. from sqlalchemy import desc
  8. s=select([cookies.c.cookie_name,cookies.c.quantity]).order_by(desc(cookies.c.quantity))
  9. rp=connection.execute(s)
  10. for cookie in rp:
  11. print ('{} - {}'.format(cookie.quantity,cookie.cookie_name))
  12. #限制条数
  13. s=select([cookies.c.cookie_name,cookies.c.quantity])
  14. s=s.order_by(cookies.c.quantity)
  15. s=s.limit(2)
  16. rp=connection.execute(s)
  17. print ([result.cookie_name for result in rp])

内嵌入sql函数:sum/count等

  1. from sqlalchemy.sql import select
  2. from sqlalchemy import MetaData
  3. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  4. metadata=MetaData()
  5. cookies = Table('cookies', metadata,
  6. Column('cookie_id', Integer(), primary_key=True),
  7. Column('cookie_name', String(50), index=True),
  8. Column('cookie_recipe_url', String(255)),
  9. Column('cookie_sku', String(55)),
  10. Column('quantity', Integer()),
  11. Column('unit_cost', Numeric(12, 2))
  12. )
  13. engine=create_engine('mysql://root:root@localhost/imooc')
  14. connection=engine.connect()
  15. #内嵌入sql函数
  16. # 如sum,count等,它打包在column(s)方法中
  17. from sqlalchemy.sql import func
  18. s=select([func.sum(cookies.c.quantity)])
  19. rp=connection.execute(s)
  20. print rp #rp是一个对象
  21. print(rp.scalar()) #取rp对象里的值 #返回结果是:151
  22. #计数
  23. s=select([func.count(cookies.c.cookie_name)])
  24. rp=connection.execute(s)
  25. record=rp.first()
  26. print (record.keys())
  27. print (record.count_1) #count总计多少条记录,列名为count_1
  28. #返回结果如下
  29. # [u'count_1']
  30. # 6
  31. #count列也可以用label取个别名
  32. s=select([func.count(cookies.c.cookie_name).label('inventory_count')])
  33. rp=connection.execute(s)
  34. record=rp.first()
  35. print (record.keys())
  36. print (record.inventory_count)
  37. #返回的结果:
  38. # ['inventory_count']
  39. # 6

过滤:where

  1. #where过滤条件
  2. #cookies.c. c相当于column
  3. s=select([cookies]).where(cookies.c.cookie_name=='chocolate chip')
  4. rp=connection.execute(s)
  5. record=rp.first()
  6. print(record.items())
  7. #like模糊过滤查找
  8. s=select([cookies]).where(cookies.c.cookie_name.like('%chocolate%'))
  9. rp=connection.execute(s)
  10. for record in rp.fetchall():
  11. print (record.cookie_name)
  1. 过滤条件中常用的方法:
  2. between(cleft,cright)
  3. concat(column_two)
  4. distinct()
  5. in_([list])
  6. is_(None)
  7. contains(string)
  8. endswith(string)
  9. like(string)
  10. startswith(string)
  11. ilike(string)

操作:

  1. from sqlalchemy.sql import select
  2. from sqlalchemy import MetaData
  3. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  4. metadata=MetaData()
  5. cookies = Table('cookies', metadata,
  6. Column('cookie_id', Integer(), primary_key=True),
  7. Column('cookie_name', String(50), index=True),
  8. Column('cookie_recipe_url', String(255)),
  9. Column('cookie_sku', String(55)),
  10. Column('quantity', Integer()),
  11. Column('unit_cost', Numeric(12, 2))
  12. )
  13. engine=create_engine('mysql://root:root@localhost/imooc')
  14. connection=engine.connect()
  15. #字符串连接:'+'
  16. s=select([cookies.c.cookie_name,'SKU-'+cookies.c.cookie_sku])
  17. for row in connection.execute(s):
  18. print(row)
  19. #cast
  20. from sqlalchemy import cast
  21. s=select([cookies.c.cookie_name,cast((cookies.c.quantity * cookies.c.unit_cost),
  22. Numeric(12,2)).label('inv_cost')])
  23. for row in connection.execute(s):
  24. print ('{} - {}'.format(row.cookie_name,row.inv_cost))
  25. #布尔型(&,|,and)
  26. #若想得到(A<B) & (C<D)用连接更高效
  27. #连接conjunctions
  28. # and_
  29. from sqlalchemy import and_,or_,not_
  30. s=select([cookies]).where(
  31. and_(
  32. cookies.c.quantity>23,
  33. cookies.c.unit_cost<0.40
  34. )
  35. )
  36. for row in connection.execute(s):
  37. print (row.cookie_name)
  38. # or_
  39. s=select([cookies]).where(
  40. or_(
  41. cookies.c.quantity.between(10,50),
  42. cookies.c.cookie_name.contains('chip')
  43. )
  44. )
  45. for row in connection.execute(s):
  46. print(row.cookie_name)

更新:update

  1. from sqlalchemy import update
  2. from sqlalchemy import select
  3. from sqlalchemy import MetaData
  4. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  5. metadata=MetaData()
  6. cookies = Table('cookies', metadata,
  7. Column('cookie_id', Integer(), primary_key=True),
  8. Column('cookie_name', String(50), index=True),
  9. Column('cookie_recipe_url', String(255)),
  10. Column('cookie_sku', String(55)),
  11. Column('quantity', Integer()),
  12. Column('unit_cost', Numeric(12, 2))
  13. )
  14. engine=create_engine('mysql://root:root@localhost/imooc')
  15. connection=engine.connect()
  16. u=update(cookies).where(cookies.c.cookie_name=='chocolate chip')
  17. u=u.values(quantity=(cookies.c.quantity+120))
  18. result=connection.execute(u)
  19. print (result.rowcount)
  20. s=select([cookies]).where(cookies.c.cookie_name=='chocolate chip')
  21. result=connection.execute(s).first()
  22. for key in result.keys():
  23. print('{:>20}:{}'.format(key,result[key]))

删除:Delete

  1. from sqlalchemy import delete
  2. from sqlalchemy import select
  3. from sqlalchemy import MetaData
  4. from sqlalchemy import (Table,Column,Integer,Numeric,String,ForeignKey,create_engine,connectors)
  5. metadata=MetaData()
  6. cookies = Table('cookies', metadata,
  7. Column('cookie_id', Integer(), primary_key=True),
  8. Column('cookie_name', String(50), index=True),
  9. Column('cookie_recipe_url', String(255)),
  10. Column('cookie_sku', String(55)),
  11. Column('quantity', Integer()),
  12. Column('unit_cost', Numeric(12, 2))
  13. )
  14. engine=create_engine('mysql://root:root@localhost/imooc')
  15. connection=engine.connect()
  16. u=delete(cookies).where(cookies.c.cookie_name=='dark chocolate chip')
  17. result=connection.execute(u)
  18. print (result.rowcount)
  19. s=select([cookies]).where(cookies.c.cookie_name=='dark chocolate chip')
  20. result=connection.execute(s)
  21. print (len(result))




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/613297
推荐阅读
相关标签
  

闽ICP备14008679号