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

相关文章

python中对_init_的理解及实例解析

python中对_init_的理解及实例解析

一、self的位置是出现在哪里? 首先,self是在类的方法中的,在调用此方法时,不用给self赋值,Python会自动给他赋值,而且这个值就是类的实例--对象本身。也可以将self换成...

Python 函数list&read&seek详解

Python 函数list&read&seek详解

一、函数list (1)定义:用打开的文件作为参数,把文件内的每一行内容作为一个元素 (2)格式:list(文件) (3)例子: with open(r"test01.txt",'r...

12个Python程序员面试必备问题与答案(小结)

12个Python程序员面试必备问题与答案(小结)

1. 什么是pickling和unpickling? Pickle模块读入任何Python对象,将它们转换成字符串,然后使用dump函数将其转储到一个文件中——这个过程叫做picklin...

举例讲解Python面相对象编程中对象的属性与类的方法

python 对象的属性 进入正题,来看一个实例来了解python中类,对象中公有属性,私有属性及局部变量,全局变量的区别. root@10.1.6.200:~# cat objec...

Numpy中矩阵matrix读取一列的方法及数组和矩阵的相互转换实例

Numpy matrix 必须是2维的,但是 numpy arrays (ndarrays) 可以是多维的(1D,2D,3D····ND),matrix是Array的一个小的分支,包含于...