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

相关文章

11月编程语言排行榜 Python逆袭C#上升到第4

11月编程语言排行榜 Python逆袭C#上升到第4

TIOBE 11 月编程语言排行榜,Python 逆袭C# 曾经有一段时间,脚本语言因其易于编写和易于运行的特性,被预测在未来将发展强大。因此,Perl,Python,PHP 和 Rub...

python实现Zabbix-API监控

python实现Zabbix-API监控

  做运维的朋友应该知道,公司IDC机房经常有上架、下架、报修和报废的服务器。如果服务器数量很多的时候很容易造成监控遗漏。      ...

简单了解python单例模式的几种写法

方法一:使用装饰器 装饰器维护一个字典对象instances,缓存了所有单例类,只要单例不存在则创建,已经存在直接返回该实例对象。 def singleton(cls): inst...

TensorFlow tensor的拼接实例

TensorFlow提供两种类型的拼接: tf.concat(values, axis, name='concat'):按照指定的已经存在的轴进行拼接 tf.stack(values...

对python xlrd读取datetime类型数据的方法详解

使用xlrd读取出来的时间字段是类似41410.5083333的浮点数,在使用时需要转换成对应的datetime类型,下面代码是转换的方法: 首先需要引入xldate_as_tuple函...