python 訪問數據庫一:添加部門

import MySQLdb
import random
import string
'''conn = MySQLdb.connect(host='192.168.*.**',
        port = ****,
        user='*****',
        passwd='****',
        db ='****'
)
cur = conn.cursor()


#一次插入多條記錄 executemany
sqli="insert into t_department(ParentDepID,DepName,Status,CreateDate,CompanyId) values(%s,%s,%s,%s,%s)"
cur.executemany(sqli,[
    ('50020','Tom','1','2017-05-16 15:41:02','39375'),
    ('50020','Jack','1','2017-05-16 15:41:02','39375'),
    ])
print "update success"
cur.close()
conn.commit()
conn.close()'''
#################################################################插入單條操作
def addDepartment():


'conn = MySQLdb.connect(host='192.168.*.**',
        port = ****,
        user='*****',
        passwd='****',
        db ='****'
)
cur = conn.cursor()
comid = raw_input("Input your companyid: ")
times = raw_input("Input your department number to increase: ") 
num = int(times)
for i in range (1,num+1):

sqli="insert into t_department(ParentDepID,DepName,Status,CreateDate,CompanyId) values(%s,%s,%s,%s,%s)"
param=('50020','name','1','2017-05-16 15:41:02',comid)


cur.execute(sqli,param)





print "update success"
cur.execute("select count(*) from t_department where CompanyId = 39375 ")
result = cur.fetchmany()


print("該公司部門總數量: %s" % (result))
cur.close()
conn.commit()
conn.close()
if __name__ == "__main__":

    addDepartment()

################################################嘗試用定義函數,分層

def openConn():
conn = MySQLdb.connect(host='192.168.*.**',
        port = ****,
        user='*****',
        passwd='****',
        db ='****'
)
return conn
def addDepartment():

con = openConn()
cur = con.cursor()
comid = raw_input("Input your companyid: ")
times = raw_input("Input your department number to increase: ") 
num = int(times)
for i in range (1,num+1):

sqli="insert into t_department(ParentDepID,DepName,Status,CreateDate,CompanyId) values(%s,%s,%s,%s,%s)"
param=('50020','name','1','2017-05-16 15:41:02',comid)
cur.execute(sqli,param)


print "update success"
cur.execute("select count(*) from t_department where CompanyId = 39375 ")
result = cur.fetchmany()


print("該公司部門總數量: %s" % (result))
cur.close()
con.commit()
con.close()
if __name__ == "__main__":
    addDepartment()

 

發佈了67 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章