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切分字符串的一个不错方法

一同事问:有一字符串“abcdefghijklmn”如何用Python来切分,每四个一段,剩下的算一段。字符段切分,首先会想到split()和 re.split()函数,但仔细想了一下,...

Numpy数组的保存与读取方法

1. 数组以二进制格式保存 np.save和np.load是读写磁盘数组数据的两个主要函数。默认情况下,数组以未压缩的原始二进制格式保存在扩展名为npy的文件中,以数组a为例 np....

python 搜索大文件的实例代码

如下所示: import os,os.path def getBigFile(pathname,filesize):#第一个参数为要遍历的文件夹,第二个是要找的最小文件的大小...

Python编程图形库之Pillow使用方法讲解

Python编程图形库之Pillow使用方法讲解

PIL vs Pillow PIL: Python Imaging Library,是python的图像处理库。由于PIL不兼容setuptools,再加上更新缓慢等因素,Alex Cl...

Python 过滤错误log并导出的实例

前言: 测试过程中获取App相关log后,如何快速找出crash的部分,并导出到新的文件呢? 感兴趣的话,继续往下看吧~ 思路:遍历多个日志文件,找出含有Error和Crash的日志,并...