python之连接Mysql实现增删改查

Python2.7使用MySQLdb接口连接Mysql,Python3改用了pymysql

 

通用方法是:

import pymysql

#连接数据库
database = pymysql.connect(host="XXXXXXXXXX.mysql.rds.aliyuncs.com",user="xxxxxx_rw",
        passwd="xxxxxxxxxx",
        db="xxxxxxxxx",
        charset='utf8')
cursor = database.cursor()# 使用cursor()方法获取操作游标 
sql_select = "select count(id) from xxxxx"# SQL 操作,增删改查, 下面是一个查询语句

try:  
   cursor.execute(sql_select) # 执行SQL语句
   db.commit()# 提交修改
except:
   db.rollback()  # 发生错误时回滚


db.close()# 关闭连接


下面是一个例子,实现把离线excel数据解析并导入到线上云服务器中的RDS。

#encoding=utf-8

import xlrd from configparser 
import ConfigParser
import pymysql
import sys

try:
	book = xlrd.open_workbook("xxxxxx.xlsx")  #文件名,把文件与py文件放在同一目录下
except:
	print("open excel file failed!")
try:
	sheet = book.sheet_by_name("工作表1")   #execl里面的worksheet1
except:
	print("locate worksheet in excel failed!")

try:
	#连接数据库
	database = pymysql.connect(host="XXXXXXXXXX.mysql.rds.aliyuncs.com",user="xxxxxx_rw",
        passwd="xxxxxxxxxx",
        db="xxxxxxxxx",
        charset='utf8')
except:
	print("Could not connect to mysql server(XXXXXXXXXX.mysql.rds.aliyun.com)")

cursor = database.cursor()

select = "select count(id) from xxxxx" #获取表中xxxxx记录数

cursor.execute(select) #执行sql语句
line_count = cursor.fetchone()
#print(line_count[0])

for i in range(1, sheet.nrows): #第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1

	intention_type = sheet.cell(i,0).value #取第i行第0列
	iphone = sheet.cell(i,1).value#取第i行第1列,下面依次类推
	addrs = sheet.cell(i,2).value
	intention_date = sheet.cell(i,3).value
	uname = sheet.cell(i,4).value
	ID_card = sheet.cell(i,5).value
	intention_car = sheet.cell(i,6).value
	comment = sheet.cell(i,7).value
#	create_time = now()
	value = (uname,ID_card,iphone,addrs,intention_car,intention_type,intention_date,comment)
	insert = "INSERT INTO dm_intention_pool(name,id_card_no,mobile,addr,model_code,type,intention_time,ext)VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"
	cursor.execute(insert,value) #执行sql语句


update = "UPDATE `xxxxx`  SET `create_time` =now(),`update_time` =now() where id > %s"

try:
	#执行sql语句
	cursor.execute(update,line_count[0]) 
	#提交到DB执行
	database.commit()
except:
	db.rollback()

cursor.close() #关闭连接
database.close()#关闭数据
print (""+Done! ")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值