Python实现MySQL数据库连接---pymysql
import json
import pymysql
import time
import traceback
fo = open('./DouBanTOP250_info_primary.txt', 'r')
info = json.load(fo)
fo.close()
conn = pymysql.connect(
user = 'YourUserName',
password = 'YourPassword',
# MySQL的默认端口为3306
port = 3306,
# 本机地址为127.0.0.1或localhost
host = '127.0.0.1',
# 指定使用的数据库
init_command = 'use DouBanTOP250_info'
)
# 创建游标对象
cur = conn.cursor()
init_command是在数据库连接成功后执行的SQL语句,
其中
use DouBanTOP250_info
的含义是使用数据库DouBanTOP250_info,故可以使用pymysql.connect()的database参数代替
即:
conn = pymysql.connect(
user = 'YourUserName',
password = 'YourPassword',
# MySQL的默认端口为3306
port = 3306,
# 本机地址为127.0.0.1或localhost
host = '127.0.0.1',
# 指定使用的数据库
database = 'DouBanTOP250_info'
)
# 创建游标对象
cur = conn.cursor()
上述的两种写法是等效的。
# 创建表的SQL语句
SQL = 'create table if not exists info('\
'id int primary key,' \
'title char not null,' \
'photo_src char not null)'
try:
# 开启一个事务
conn.begin()
# 设置将执行的SQL语句
cur.execute(SQL)
# 提交事务
conn.commit()
except Exception:
print('【初始化失败(表)】')
# 打印错误信息
print(' ', traceback.print_exc())
pass
traceback.print_exc(file=fo)
其中fo是一个文件对象,可以使用open()函数创建
可将错误信息输出到指定的文件(fo)中。
start = time.time()
# 将数据插入到目标数据库的指定表中
try:
# 开启一个事务
conn.begin()
for item in info.values():
cur.execute('insert into info (title, photo_src) values(%s, %s)', [item['title'], item['photo_src']])
# 提交事务
conn.commit()
# 记录处理时间
process_time = time.time() - start
# 打印处理时间
print(process_time)
except Exception:
print('【插入数据失败】')
# 打印错误信息
print(traceback.print_exc())
pass
# 关闭游标
cur.close()
# 关闭连接
conn.close()
cur.execute(‘insert into info (title, photo_src) values(%s, %s)’, [item[‘title’], item[‘photo_src’]])
不要直接拼接字符串来构造需要执行的SQL语句,推荐使用参数完成构造,理由有二:
- 参数SQL会被系统缓存,当多次执行同一语句时,无需对SQL进行反复编译。
- 可防止SQL注入。
注:
短时间有大量不同的SQL语句需要循环执行时,在条件允许的情况下,应在循环结束后提交事务。
若使用下述代码(每循环一次提交一次事务):
start = time.time()
# 将数据插入到目标数据库的指定表中
try:
# 开启一个事务
conn.begin()
for item in info.values():
cur.execute('insert into info (title, photo_src) values(%s, %s)', [item['title'], item['photo_src']])
# 提交事务 <-------------------------改动一处
conn.commit()
# 记录处理时间
process_time = time.time() - start
# 打印处理时间
print(process_time)
except Exception:
print('【插入数据失败】')
# 打印错误信息
print(traceback.print_exc())
pass
# 关闭游标
cur.close()
# 关闭连接
conn.close()
花费时间将由原来的1.5s(平均)上升到7.5s(平均),性能方面将出现很大的损失。
# 导入模块
import json
import pymysql
import time
import traceback
# 读取JSON文件,并将其转换为Python数据格式--字典
fo = open('./DouBanTOP250_info_primary.txt', 'r')
info = json.load(fo)
fo.close()
# 连接数据库管理系统
conn = pymysql.connect(
user = 'YourUserName',
password = 'YourPassword',
# MySQL的默认端口为3306
port = 3306,
# 本机地址为127.0.0.1或localhost
host = '127.0.0.1',
# 指定使用的数据库
init_command = 'use DouBanTOP250_info'
# 上述语句可使用
# database = DouBanTOP250_info
# 进行替换
)
# 创建游标对象
cur = conn.cursor()
# 初始化操作(在指定的表不存在时,创建一张表)
# 创建表的SQL语句
SQL = 'create table if not exists info('\
'id int primary key,' \
'title char not null,' \
'photo_src char not null)'
try:
# 开启一个事务
conn.begin()
# 设置将执行的SQL语句
cur.execute(SQL)
# 提交事务
conn.commit()
except Exception:
print('【初始化失败(表)】')
# 打印错误信息
print(' ', traceback.print_exc())
# traceback.print_exc(file=fo)
# (其中fo是一个文件对象,可以使用open()函数创建)
# 可将错误信息输出到指定的文件(fo)中。
pass
# 布置计时器
start = time.time()
# 将数据插入到目标数据库的指定表中
try:
# 开启一个事务
conn.begin()
for item in info.values():
# 不要直接拼接字符串来构造需要执行的SQL语句,推荐使用参数完成构造,理由有二:
# (cur.execute(SQL, args)
# 1. 参数SQL会被系统缓存,当多次执行同一语句时,无需对SQL进行反复编译。
# 2. 可防止SQL注入
cur.execute('insert into info (title, photo_src) values(%s, %s)', [item['title'], item['photo_src']])
# 提交事务
conn.commit()
# 记录处理时间
process_time = time.time() - start
# 打印处理时间
print(process_time)
except Exception:
print('【插入数据失败】')
# 打印错误信息
print(traceback.print_exc())
pass
# 关闭游标
cur.close()
# 关闭连接
conn.close()
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_
无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD