云扳手API客户端库
google-cloud-spanner的Python项目详细描述
Cloud Spanner是世界上第一个完全托管的关系数据库服务 为 关键任务在线事务处理(OLTP)应用程序有云的 扳手您可以享受关系数据库的所有传统好处;但是 与其他关系数据库服务不同,cloud扳手可以水平扩展 到成百上千的服务器来处理最大的事务 工作量。
快速启动
要使用此库,首先需要执行以下步骤:
- Select or create a Cloud Platform project.
- Enable billing for your project.
- Enable the Google Cloud Spanner API.
- Setup Authentication.
安装
使用pip在virtualenv中安装此库virtualenv是 创建独立的python环境。它解决的基本问题是 依赖项和版本,以及间接权限。
使用virtualenv,无需系统即可安装此库 安装权限,且不会与已安装的系统发生冲突 依赖关系。
支持的python版本
python=3.5
不推荐的python版本
python==2.7。Python2.7支持将于2020年1月1日取消。
Mac/Linux
pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-spanner
窗口
pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-spanner
示例用法
在事务中执行任意sql
一般来说,要使用云扳手,您需要一个事务这个 首选的机制是创建一个单独的函数,它执行 作为对database.run_in_transaction:
的回调# First, define the function that represents a single "unit of work"# that should be run within the transaction.defupdate_anniversary(transaction,person_id,unix_timestamp):# The query itself is just a string.## The use of @parameters is recommended rather than doing your# own string interpolation; this provides protections against# SQL injection attacks.query="""SELECT anniversary FROM people WHERE id = @person_id"""# When executing the SQL statement, the query and parameters are sent# as separate arguments. When using parameters, you must specify# both the parameters themselves and their types.row=transaction.execute_sql(query=query,params={'person_id':person_id},param_types={'person_id':types.INT64_PARAM_TYPE,},).one()# Now perform an update on the data.old_anniversary=row[0]new_anniversary=_compute_anniversary(old_anniversary,years)transaction.update('people',['person_id','anniversary'],[person_id,new_anniversary],)# Actually run the `update_anniversary` function in a transaction.database.run_in_transaction(update_anniversary,person_id=42,unix_timestamp=1335020400,)
使用事务选择记录
一旦有了事务对象(例如第一个参数发送到 run_in_transaction,读取数据很容易:
# Define a SELECT query.query="""SELECT e.first_name, e.last_name, p.telephone FROM employees as e, phones as p WHERE p.employee_id == e.employee_id"""# Execute the query and return results.result=transaction.execute_sql(query)forrowinresult.rows:print(row)
使用事务插入记录
要向表中添加一个或多个记录,请使用insert:
transaction.insert('citizens',columns=['email','first_name','last_name','age'],values=[['phred@exammple.com','Phred','Phlyntstone',32],['bharney@example.com','Bharney','Rhubble',31],],)
使用事务更新记录
^ tT4}$更新表中的一个或多个现有记录。失败 如果任何记录都不存在。
transaction.update('citizens',columns=['email','age'],values=[['phred@exammple.com',33],['bharney@example.com',32],],)
下一步
- 查看Client Library Documentation了解如何连接到云 使用此客户端库的扳手。
- 阅读Product documentation学习 有关产品的更多信息,请参见如何指导。