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 cv2在验证码识别中应用实例解析

这篇文章主要介绍了python cv2在验证码识别中应用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用函数cv2.imr...

python关于调用函数外的变量实例

实例如下所示: class Solution(object): def foo(self, s): def bar(a): s += a prin...

深入flask之异步非堵塞实现代码示例

官方其实已经给出了方案,只不过藏的有点深,在加上网上有很多不太靠谱的帖子误导了我(当然不排除我没理解的原因哈)。所以为了让有些朋友的少走点弯路,也为给自己做个备忘。 完整代码:https...

python实现AES和RSA加解密的方法

本文实例为大家分享了python实现AES和RSA加解密的具体代码,供大家参考,具体内容如下 AES AES 是一种对称加密算法,用key对一段text加密,则用同一个key对密文解密,...

pytorch 共享参数的示例

在很多神经网络中,往往会出现多个层共享一个权重的情况,pytorch可以快速地处理权重共享问题。 例子1: class ConvNet(nn.Module): def __ini...