python访问mysql数据库的实现方法(2则示例)

yipeiwu_com5年前Python基础

本文实例讲述了python访问mysql数据库的实现方法。分享给大家供大家参考,具体如下:

首先安装与Python版本匹配的MySQLdb

示例一

import MySQLdb
conn=MySQLdb.connect(user='root',passwd='123',db='example')
cur=conn.cursor()
cur.execute("select id,lastname,firstname, date_format(dob,'%Y-%m-%d %H-%i-%s'),phone from employee")
##select username,password, date_format(reg_date,'%Y-%m-%d %H-%i-%s') as date from reg_user
for data in cur.fetchall():
  print data
cur.close()
conn.commit()
conn.close()

示例二

import MySQLdb
conn = MySQLdb.connect(host='localhost',user='root',passwd='')
cursor = conn.cursor()
cursor.execute("create database python")
cursor.execute('use python')
cursor.execute("create table test(id int, content varchar(100))")
#插入一条100条数据
for i in range(1,100):
   cursor.execute("insert into test values(%s,%s)",[i,'haha'])
#获取数据
cursor.execute('select * from test')
results = cursor.fetchall()
for r in results
   print r
conn.close()

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python读取excel指定列生成指定sql脚本的方法

需求 最近公司干活,收到一个需求,说是让手动将数据库查出来的信息复制粘贴到excel中,在用excel中写好的公式将指定的两列数据用update这样的语句替换掉。 例如: 有个A库,其...

python 字典操作提取key,value的方法

python 字典操作提取key,value的方法

python 字典操作提取key,value dictionaryName[key] = value 1.为字典增加一项 2.访问字典中的值 3、删除字典中的一项...

Django1.11自带分页器paginator的使用方法

本文实例为大家分享了Django1.11自带分页器Django的具体使用方法,供大家参考,具体内容如下 接下来我编写一个 views ,名classify。 classify,将模拟请...

Python操作redis实例小结【String、Hash、List、Set等】

本文实例总结了Python操作redis方法。分享给大家供大家参考,具体如下: python连接方式可参考:/post/161353.htm 这里介绍详细使用 1、String 操作 r...

5个很好的Python面试题问题答案及分析

本文的主要内容是向大家分享几个Python面试中的T题目,同时给出了答案并对其进行分析,具体如下。 本文的原文是5 Great Python Interview Questions,同时...