python sqlserver 传参
2018-06-01 本文已影响269人
啊哈JC熙
import pymssql
import pandas as pd
class SqlSearch(object):
def __init__(self):
self.get_conn()
def get_conn(self):
try:
self.conn = pymssql.connect(
host = "127.0.0.1",
user = "sa",
password = "ljc123",
database = "Iris_Data",
charset = 'utf8'
)
except Exception as e:
print("Error : %s" % e)
def close_conn(self):
try:
if self.conn:
self.conn.close()
except Exception as e:
print("Error: %s" % e)
def ExecQuery(self, tablename):
print(tablename)
sql = "select * from %s"%tablename
print(sql)
cursor = self.conn.cursor()
cursor.execute(sql, tablename)
resList = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall() ]
self.conn.close()
return resList
def Query(self):
sql = ("select * from iris;")
cursor = self.conn.cursor()
cursor.execute(sql)
# 转换为字典的形式化
resList = [dict(zip([k[0] for k in cursor.description], row))
for row in cursor.fetchall() ]
self.conn.close()
return resList
def add_one(self,sepal_length, sepal_width, petal_length, petal_width, target):
try:
sql =(
"INSERT INTO `iris` VALUE ( %s, %s, %s, %s, %s );"
)
cursor = self.conn.cursor()
cursor.execute(sql, (sepal_length, sepal_width, petal_length, petal_width, target))
self.conn.commit()
cursor.close()
except :
print("Error")
self.conn.rollback()
self.close_conn()
def add_more(self):
try:
sql =(
"INSERT INTO iris VALUES ( %s, %s, %s, %s, %s );"
)
cursor = self.conn.cursor()
df = pd.DataFrame(pd.read_csv('iris.csv',header=None))
for index in df.index:
sepal_length = df.loc[index].values[0]
sepal_width = df.loc[index].values[1]
petal_length = df.loc[index].values[2]
petal_width = df.loc[index].values[3]
target = df.loc[index].values[4]
print(sepal_length, sepal_width, petal_length, petal_width, target)
cursor.execute(sql, (sepal_length, sepal_width, petal_length, petal_width, target))
self.conn.commit()
cursor.close()
except :
print("Error")
self.conn.rollback()
self.close_conn()
pass
"""
传参数编程规范:
def initPgSql(self,tablename,count):
columns=[]
for i in range(count):
columns.append("%s")
strs=",".join(columns)
sql="INSERT INTO %s%s VALUES(%s)"%(TableSpace,tablename,strs)
return sql
"""
def main():
obj = SqlSearch()
#obj.add_more()
#print(obj.Query())
print(obj.ExecQuery("iris"))
print("************************** Finish **************************")
if __name__ == '__main__':
main()