Python连接数据库

来源:互联网 发布:村上作品推荐 知乎 编辑:程序博客网 时间:2024/06/16 00:12
import MySQLdb#查询conn = MySQLdb.Connect(host='127.0.0.1',port=3306,user='root',passwd='123456',db='IMOOC',charset='utf8')cur = conn.cursor()sql="select * from user"cur.execute(sql)rs = cur.fetchall()for row in rs:    print 'userid=%d,username=%s'%rowcur.close()conn.close()


#更新删除

sql_insert = 'insert into stud(userid, username) values("12","name12")'sql_upudate = 'update stud set username="name19"  where userid="9"'sql_insert = 'delete from stud where userid<"3"'try:    cursor.execute(sql_insert)    print cursor.rowcount    cursor.execute(sql_upudate)    print cursor.rowcount    cursor.execute(sql_insert)    print cursor.rowcount        conn.commit()except Exception as e:    print e    conn.rollback()

原创粉丝点击