python访问mysql数据库的实现方法(2则示例)

本文实例讲述了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程序设计有所帮助。

相关文章

在前一篇博客中我们介绍了加侧旋的乒乓球弧圈技术的模拟,本...
在近期conda的版本更新中,有可能会删除路径下的_sysconfigd...
本文主要展示了一些lambda表达式的使用示例,通过这些示例,...
本文通过对比Jax和Numpy计算Normalized Hamming Distance的过...
我们知道GPU加速在可并行化程度比较高的算法中,能够发挥出比...
Numpy这个库在Python编程中非常的常用,不仅在性能上补足了P...