python操作数据库

本文提供了一个使用 Python 的 MySQLdb 库连接 MySQL 数据库并进行数据读取及插入操作的示例。示例中展示了如何连接数据库、执行 SQL 查询语句获取数据,并通过 Python 执行批量插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#-*- coding: UTF-8 -*- 
import MySQLdb
try:
   connection = MySQLdb.connect(user="root",passwd="root",host="localhost",db="test",charset="utf8")
except:
   print "could not connect to mysql server."
   exit(0)
try:
   cursor = connection.cursor()
   #cursor.execute( " select * from news where id = 1 " )
   count = cursor.execute("select * from jtg_test " )
   #统计记录
   print '总共有%s条记录',count
   print " row secect:", cursor.rowcount
 
   for row in cursor.fetchall():
       print "note : ",row[0],row[1]
   cursor.close()
except:
   print "fetch error"
   exit(0)
try:
   connection.select_db('analyse_event')
   cur=connection.cursor()
   value=['bb','ccc']
   cur.execute('insert into jtg_test(name,password)values(%s,%s)',value)
#   connection.commit()
   values = []
   for i in range(20):
       values.append(('ss'+str(i),'helo'+str(i)))
   cur.executemany('insert into jtg_test(name,password)values(%s,%s)',values)
   connection.commit()
   cur.close()
   connection.close()
except:
   print "failor"
   exit(0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值