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

相关文章

python实现随机梯度下降(SGD)

使用神经网络进行样本训练,要实现随机梯度下降算法。这里我根据麦子学院彭亮老师的讲解,总结如下,(神经网络的结构在另一篇博客中已经定义): def SGD(self, training...

python实现三维拟合的方法

如下所示: from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d imp...

pygame学习笔记(6):完成一个简单的游戏

学了这么长时间的Pygame,一直想写个游戏实战一下。看起来很简单的游戏,写其来怎么这么难。最初想写个俄罗斯方块,想了很长时间如何实现,想来想去,也没写出来,于是干脆下载别人的代码来读。...

关于Python中Inf与Nan的判断问题详解

大家都知道 在Python 中可以用如下方式表示正负无穷: float("inf") # 正无穷 float("-inf") # 负无穷 利用 inf(infinite) 乘以 0...

python hashlib加密实现代码

python hashlib加密实现代码

用于加密相关的操作,代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA512,MD5算法。 以下是算法示例: #!/usr/bin/env pytho...