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基础学习之常见的内建函数整理

 前言 Python针对众多的类型,提供了众多的内建函数来处理,这些内建函数功用在于其往往可对多种类型对象进行类似的操作,即多种类型对象的共有的操作,下面话不多说了,来一看看详...

python 2.7 检测一个网页是否能正常访问的方法

如下所示: #!/bin/env python #coding:utf-8 import requests import sys url = "https://mp.csdn...

python生成带有表格的图片实例

python生成带有表格的图片实例

因为工作中需要,需要生成一个带表格的图片 例如: 直接在html中写一个table标签,然后单独把表格部分保存成图片 或者是直接将excel中的内容保存成一个图片 刚开始的思路,是直接生...

python学生管理系统学习笔记

本文实例为大家分享了python学生管理系统的具体代码,供大家参考,具体内容如下 基于列表存储的学生管理系统,实现如下功能 ================== 学生管理系统 1、添加...

对Python3.x版本print函数左右对齐详解

数字的情况: a = 5 , b = 5.2,c = "123456789" 最普通的右对齐:print("%3d"%a) 输出 5(详情:5前面两个空格) print("%10.3f"...