python 操作mysql数据库(简单/基础)

1配置MySLQ

   1-1:安装mysql windows 安装mysql5.7

   1-2:安装python依赖mysql模块

          pip install mysql 安装Python的MySQL库,但是总会报错。

          常见错误如:
                              Microsoft Visual C++ 9.0 is required  (Unable to find vcvarsall.bat)
          mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory

          这些可能是驱动等问题。

         本文章采用下面的方法安装:

                下载一个MySQL-python-1.2.3.win-amd64-py2.7.exe文件进行安装。

                            官网地址:https://pypi.python.org/pypi/MySQL-python/
                 下载地址:http://download.csdn.net/detail/eastmount/9598651

                  默认安装即可。

2、引入MySQLdb库,如下:

    

import MySQLdb 
3、连接数据路

     

conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306, db='test2', charset='utf8')
  1. user:Username  
  2. password:Password  
  3. host:Hostname  
  4. database:DatabaseName
conn为连接对象  
  1. lose():关闭数据库连接,或者关闭游标对象  
  2. commit():提交当前事务  
  3. rollback():取消当前事务  
  4. cursor():创建游标或类游标对象  
  5. errorhandler(cxn,errcls,errval):作为已给游标的句

游标对象:

        fetchone():可以看作fetch(取出) one(一个),也就是得到结果集的下一行(一行)。  

        fetchmany(size):可以看作fetch(取出)many(多个),这里的参数是界限,得到结果集的下几行(几行)  
        fetchall():顾名思义,取得所有。  
        execute(sql):执行数据库操作,参数为sql语句。  
        close():不需要游标时尽可能的关闭 

下面是整个python连接mysql实例

# coding:utf-8
import MySQLdb  
   
try:  
	conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)  
	cur=conn.cursor()  
	res = cur.execute('show databases')  
	print res  
	for data in cur.fetchall():  
		print '%s' % data  
	cur.close()  
	conn.close()  
except MySQLdb.Error,e:  
	 print "Mysql Error %d: %s" % (e.args[0], e.args[1])  

查询数据并写入mysqlDB文件:

import MySQLdb
import datetime
import time



def  isDate(datetime):
	try:
		datetime.strftime('%Y-%m-%d')
		return True
	except Exception as e:
		return False
try:  
    conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306,db='test2')  
    cur=conn.cursor()  
    res = cur.execute('select * from t_user')  
    print res  
    for data in cur.fetchall():  
        for x in data:
        	if isDate(x):
        		if x=='':
        			x='NULL'
        		open('userDB.txt','a+').write(x.strftime('%Y-%m-%d')+"\n")
        	else:
        		if x=='':
        			x='NULL'
        		open('userDB.txt','a+').write(x+"\n")
        		print x
        	
    cur.close()  
    conn.close()  
except MySQLdb.Error,e:  
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])  





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值