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

相关文章

Django 请求Request的具体使用方法

Django 请求Request的具体使用方法

1 URL路径参数 在定义路由URL时,使用正则表达式提取参数的方法从URL中获取请求参数,Django会将提取的参数直接传递到视图的传入参数中。 未命名参数按顺序传递, 如 url...

pandas创建新Dataframe并添加多行的实例

处理数据的时候,偶然遇到要把一个Dataframe中的某些行添加至一个空白的Dataframe中的问题。 最先想到的方法是创建Dataframe,从原有的Dataframe中逐行筛选出指...

Python程序员鲜为人知但你应该知道的17个问题

一、不要使用可变对象作为函数默认值复制代码 代码如下:In [1]: def append_to_list(value, def_list=[]):   ...:&n...

解决python升级引起的pip执行错误的问题

centos6.x默认安装的python为2.6版本,今天换成了3.5版本 这里不再讲如何升级python版本 在安装完新的版本后,之前安装的插件都不能使用了,再用pip进行安装提示已经...

NumPy 数学函数及代数运算的实现代码

一、实验介绍 1.1 实验内容 如果你使用 Python 语言进行科学计算,那么一定会接触到NumPy。NumPy 是支持 Python 语言的数值计算扩充库,其拥有强大的多维数组处...