使用mysql-connector-python操作MYSQL数据库

#!/usr/bin/python # encoding:utf-8 # 需要依赖mysql客户端: pip install mysql-connector-python import os, sys, string import mysql.connector import sys sys.setdefaultencoding('utf-8') def main(): # connect to mysql try: conn = mysql.connector.connect(host='10.201.*.*', user='root', passwd='root', db='dbname') except Exception, e: print e sys.exit() # get cursor cursor = conn.cursor() # create table dropSql='drop table product' createSql = 'create table if not exists product(Prd_name varchar(128) primary key, Count int(4))' cursor.execute(dropSql) cursor.execute(createSql) # insert one data sql = "insert into product(Prd_name, Count) values('%s', %d)" % ("ATG", 200) try: cursor.execute(sql) except Exception, e: print e # insert some datas sql = "insert into product(Prd_name, Count) values(%s, %s)" val = (("PPS", 400), ("暗恋我", 150), ("你好测试1", 25)) try: cursor.executemany(sql, val) except Exception, e: print e conn.commit() # quary data sql = "select * from product" cursor.execute(sql) alldata = cursor.fetchall() # print data if alldata: for rec in alldata: print rec[0], rec[1] cursor.close() conn.close() if __name__ == "__main__": main() print("\nIt's OK")
上一篇:云上中国年,阿里云CDN猪年春节高峰流量再创新高


下一篇:IDEA 初始配置教程