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

相关文章

elasticsearch python 查询的两种方法

elasticsearch python 查询的两种方法

elasticsearch python 查询的两种方法,具体内容如下所述: from elasticsearch import Elasticsearch es = Elastic...

Python进行数据科学工作的简单入门教程

Python进行数据科学工作的简单入门教程

Python拥有着极其丰富且稳定的数据科学工具环境。遗憾的是,对不了解的人来说这个环境犹如丛林一般(cue snake joke)。在这篇文章中,我会一步一步指导你怎么进入这个PyDat...

Python数据结构之翻转链表

翻转一个链表 样例:给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null 一种比较简单的方法是用“摘除法”。就是先...

django框架之cookie/session的使用示例(小结)

一、http协议无状态问题 http协议没有提供多次请求之间的关联功能,协议的本意也并未考虑到多次请求之间的状态维持,每一次请求都被协议认为是一次性的。但在某些场景下,如一次登录多次访问...

Python文件如何引入?详解引入Python文件步骤

Python文件如何引入?详解引入Python文件步骤

python基本语法--引入Python文件 1、新建python文件 :在同目录lib下创建mylib.py和loadlib.py两个文件 2、在mylib.py文件中创建一个Hel...