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

yipeiwu_com6年前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网络编程学习笔记(四):域名系统

一、什么是域名系统 DNS 计算机域名系统 (DNS) 是由解析器以及域名服务器组成的。当我们在上网的时候,通常输入的是网址,其实这就是一个域名,而我们计算机网络上的计算机彼此之间只能用...

python实现海螺图片的方法示例

python实现海螺图片的方法示例

本文介绍了如何用python实现海螺图片,感兴趣的可以参考一下,具体代码如下: 代码如下: import turtle import time t = turtle.Turtl...

Python数据处理篇之Sympy系列(五)---解方程

Python数据处理篇之Sympy系列(五)---解方程

前言 sympy不仅在符号运算方面强大,在解方程方面也是很强大。 本章节学习对应官网的:Solvers 官方教程 https://docs.sympy.org/latest/tutor...

详解Python中for循环是如何工作的

详解Python中for循环是如何工作的

前言 for...in 是Python程序员使用最多的语句,for 循环用于迭代容器对象中的元素,这些对象可以是列表、元组、字典、集合、文件,甚至可以是自定义类或者函数,例如: 作用于列...

python PIL和CV对 图片的读取,显示,裁剪,保存实现方法

PIL 图片操作 读取图片 img = Image.open(“a.jpg”) 显示图片 im.show() # im是Image对象,im是numpy类型,通过Image.f...