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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

关于python2 csv写入空白行的问题

关于python2 csv写入空白行的问题

如下所示: writer = csv.writer(open('xx.csv','w')) data = [('zzz', 20, 123456),('jojo', 10, 7890...

python 使用正则表达式按照多个空格分割字符的实例

python 使用正则表达式按照多个空格分割字符的实例

程序代码如下 import os import re os.system("nmap -sP 192.168.3.0/24") //扫描IP mac = os.popen("cat...

用Python将动态GIF图片倒放播放的方法

用Python将动态GIF图片倒放播放的方法

这次让我们一个用 Python 做一个小工具:将动态 GIF 图片倒序播放! GIF(Graphics Interchange Format) 是一种可以用来呈现动画效果的图片格式,原...

Python输出\u编码将其转换成中文的实例

Python输出\u编码将其转换成中文的实例

爬取了下小猪短租的网站出租房信息但是输出的时候是这种: 百度了下。python2.7在window上的编码确实是个坑 解决如下 如果是个字典的话要先将其转成字符串 导入json库 然后...

python 返回一个列表中第二大的数方法

如下所示: # 返回一个列表中第二大的数 def second(ln): max = 0 s = {} for i in range(len(ln)):...