zoukankan      html  css  js  c++  java
  • Python使用MySQLdb操作MySQL

    import MySQLdb,sys
    
    try:
        
        conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='123',db='db1')
    
    except Exception,e:
        print e
        sys.exit(0)
        
    cursor=conn.cursor()
    try:#Add
        cursor.execute("insert into table1(name,address,year) values('Jack2','ddd','2011-5-8')")    
        cursor.execute("insert into table1(id,name,address,year) values(%d,'%s','%s','%s')"%(99,"Jack","USA","1990-9-9"))    #注意,这里是'%s'是带单引号的!!!
    except Exception,e:
        print e
    try:#Delete
        cursor.execute("delete from table1 where name='Jack2'") 
    except Exception,e:
        print e  
    try:#Change
        cursor.execute("update table1 set name='YY' where address='XiAn'")
    except Exception, e:
        print e
    
    try:#AddMulti
        sql="insert into table1(name,address,year) values(%s,%s,%s)"     #而这里是%s,不带单引号的。数字怎么处理。我写个%d,在下面分别写上数字编号6,,6,666却显示错误。
        var=(("Bu1","Japan","2011-1-1"),("Bu2","Japan","2011-1-2"),("Bu3","Japan","2011-1-3"))
        cursor.executemany(sql,var)
    except Exception,e:
        print e    
    sql="select * from table1"
    try:#Search
        cursor.execute(sql)
    except Exception,e:
        print e
    rows=cursor.fetchall()
    if rows:
        for item in rows:
            print item[0],item[1],item[2],item[3]
    
    cursor.close()
    conn.close()
  • 相关阅读:
    让8个数码管全部显示数字
    程序存储空间与内存
    点亮数码管,显示具体的数字
    为什么点亮小灯时,有时是输入数字0,有时是数字1
    循环点亮LED灯
    keil 编程时,总是中英文切换时,格式混乱。
    点亮LED灯
    学生管理系统(C 大一期末作业)
    ivew ui
    git常见操作
  • 原文地址:https://www.cnblogs.com/wangjiyuan/p/caozuomysqlbypython.html
Copyright © 2011-2022 走看看