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

原创
2016/04/20 17:13
阅读数 1.4K
#!/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")
展开阅读全文
加载中

作者的其它热门文章

打赏
1
2 收藏
分享
打赏
0 评论
2 收藏
1
分享
返回顶部
顶部