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

相关文章

根据DataFrame某一列的值来选择具体的某一行方法

根据DataFrame某一列的值来选择具体的某一行方法

原始数据的DF: 此时,我要选择列名isInfected为“手足口病”的样本行: 总结:选择DataFrame里面某一列等于某个值的所有行,用一条命令即可解决即: df.loc[...

Python基于辗转相除法求解最大公约数的方法示例

Python基于辗转相除法求解最大公约数的方法示例

本文实例讲述了Python基于辗转相除法求解最大公约数的方法。分享给大家供大家参考,具体如下: 之前总结过一次高德纳TAOCP中的最大公约数求解,其实课后题中的算法修改要求实现的是辗转相...

Python实现HTTP协议下的文件下载方法总结

本文介绍了几种常用的python下载文件的方法,具体使用到了htttplib2,urllib等包,希望对大家有帮忙。 1.简单文件下载 使用htttplib2,具体代码如下: h =...

在python中将list分段并保存为array类型的方法

如下所示: list=[1,2,3,4,5,6,7,8,9,0,11,0,13,14,15,16,17,18,19,20] #把list分为长度为5的4段 for j in rang...

Python+selenium点击网页上指定坐标的实例

Python+selenium点击网页上指定坐标的实例

例如有些页面元素很难获取,但是位置很固定,那么可以直接用坐标来进行操作 例如要对页面上的(x:200, y:100)进行操作,可以用如下代码: from selenium impor...