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

相关文章

对pandas中Series的map函数详解

Series的map方法可以接受一个函数或含有映射关系的字典型对象。 使用map是一种实现元素级转换以及其他数据清理工作的便捷方式。 (DataFrame中对应的是applymap()函...

Python 实用技巧之利用Shell通配符做字符串匹配

1、需求 当工作在UNIX Shell下时,我们想使用常见的通配符模式(即:.py,Dat[0-9].csv等)来对文本做匹配。 2、解决方案 fnmatch模块提供了两个函数:fnma...

Django REST框架创建一个简单的Api实例讲解

Django REST框架创建一个简单的Api实例讲解

Create a Simple API Using Django REST Framework in Python WHAT IS AN API API stands for appli...

python通过安装itchat包实现微信自动回复收到的春节祝福

python通过安装itchat包实现微信自动回复收到的春节祝福

itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单。 开源地址 https://github.com/littlecodersh/ItChat 文档: http...

24式加速你的Python(小结)

24式加速你的Python(小结)

一,分析代码运行时间 第1式,测算代码运行时间 平凡方法 快捷方法(jupyter环境) 第2式,测算代码多次运行平均时间 平凡方法 快捷方法(jupyter环境) 第3式,按调...