使用mysql-connector-python操作MYSQL資料庫

cloudcoder發表於2016-05-13
#!/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(
It`s OK”
)



相關文章