Python连接Mysql数据库

来源:互联网 发布:盛世投资 知乎 编辑:程序博客网 时间:2024/06/07 07:54

最近对Python比较感兴趣

写了一个简单的Demo来连接一下MySQL数据库,实现了简单的增删改查询功能,但是乱码问题还未能解决,等抽时间把所有乱码问题整理一下在写一篇博客。

希望大家多多指点:

注意:

1,Python连接Mysql 数据库需要MysqlDb(MySQL-python-1.2.4b4.win32-py2.7.exe)这个是我用的,貌似不支持Python3.0的,我的Python用的2.7 的版本,MysqlDb下载好之后,直接点击会默认安装到Python的路径下(安装MySQLDb之前,MySQL也是要安装好的,mysqldb的作用就是相当于让Python能够连接到mysql中个人理解)


控制台运行截图如下:


#!/usr/bin/python

#encoding=utf-8 
import sys 
import MySQLdb  
reload(sys) 
sys.setdefaultencoding('utf-8') 
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="ait",charset='utf8') 


cursor =conn.cursor()
#删除
sql1="delete from user"
f=cursor.execute(sql1)
if(f>0):
print 'delete success'
conn.commit()


#插入
sql2='insert into user (username,password) value (11,22)' 
f=cursor.execute(sql2)
if(f>0):
print 'insert success'
conn.commit()


#修改
sql3='update user set username=123,password=456' 
f=cursor.execute(sql3)
if(f>0):
print 'update success'
conn.commit()


#查询
sql4 ="select * from user "
cursor.execute(sql4) 
row=cursor.fetchone() 
print row


#关闭
cursor.close() 
conn.close()
原创粉丝点击