python访问数据库一

直接访问mysql,示例如下:

# coding:utf-8
import time
import MySQLdb
# import traceback
# import sys

conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='dev', charset="utf8", )
cur = conn.cursor()
# cur.execute("SET NAMES utf8")

try:
    sql = "create table mytest1("
    sql = sql + "id int(11) not null auto_increment,"
    sql = sql + "channelcode varchar(100) null,"
    sql = sql + "systemcode varchar(100) not null,"
    sql = sql + "systemname varchar(100) not null,"
    sql = sql + "primary key(id))"
    print sql;
    cur.execute(sql);
except Exception, e:
    print Exception, ":", e

try:
    cur.execute("insert into mytest1(systemcode,systemname) values('test','测试')")
    conn.commit()
    print 'insert new mytest1.'
except Exception, e:
    print Exception, ":", e
    # traceback.print_exc()
# except:
#     info=sys.exc_info()
#     print info[0],":",info[1]

try:
    cur.execute("update mytest1 set systemname='测试" + time.strftime('%Y-%m-%d %H:%M:%S') + "' where systemcode='test'");
    conn.commit()
except Exception, e:
    print Exception, ":", e

try:
    itsystem = cur.execute("select * from mytest1");
    print 'count:' + str(itsystem);
    info = cur.fetchmany(itsystem)
    for ii in info:
        # if print ii,chinese string will print it's unicode with u\####
        print  str(ii[0]) + ',' + (ii[1] == None and str(None) or ii[1]) + ',' + ii[2] + ',' + ii[3]
except Exception, e:
    print Exception, ":", e

try:
    cur.execute("delete from itsystem where systemcode='test'");
    conn.commit()

    cur.execute("drop table mytest1");
except Exception, e:
    print Exception, ":", e
cur.close()
conn.close()

 

转载于:https://www.cnblogs.com/tanxstar/p/6116274.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值