Python:有一种简化sql中使用的代码的常用方法

时间:2017-06-22 08:32:59

标签: python

这是我的代码

    a1 = "a1"
    a2 = "a2"
    a3 = "a3"
    bb1 = [a1,a2]
    bb2 = [a1,a2,a3]

    db = BasicMysql(host="*",port=,user="*",password="*")
    db_values = "INSERT INTO db.bb1 values" + "('%s','%s') " %(bb1[0],bb1[1])
    db.exec_insert(db_values)  //db.exec_insert is packaged which is same as "cursor.execute(query)"

    db_values = "INSERT INTO db.bb2 values" + "('%s','%s') " %(bb2[0],bb2[1],bb2[2])
    db.exec_insert(db_values)

它可能是" db_values"的好方法/表达。任何想法?

可能是这样的伪代码:

all_sql = [bb1,bb2]
for one in all_sql:
     db_values = "????"
     db.exec_insert(db_values)

以下是我的包装MySQLdb API的API。

导入MySQLdb          class BasicMysql://定义一个类

def __init__(self,**kw):
        self.host = kw['host']
        self.port = kw['port']
        self.user = kw['user']
        self.password = kw['password']

            try:
                database_conn = MySQLdb.connect(host=self.host,port=self.port,user=self.user,passwd=self.password,local_infile
= 1,charset="utf8")
            except MySQLdb.Error, e:
                sys.exit(e)
            self.conn = database_conn

        def exec_insert(self,query):
            conn = self.conn
            cursor = conn.cursor()

            try:
                cursor.execute(query)
            except Exception,e:
                print Exception,":",e

            conn.commit()
            cursor.close()

        def __exit__(self):
            try:
                self.conn.close
            except Exception,e:
                 print Exception,":",e

1 个答案:

答案 0 :(得分:0)

我找到了当地人"这可以满足我的需求:

getVar = locals()
a1 = "a1"
a2 = "a2"
a3 = "a3"
bb1 = [a1,a2]
bb2 = [a1,a2,a3]
all_sql = [bb1,bb2]
for one in all_sql:
     db_values = ",".join([str([getVar[i]) for i in all_sql])
     db.exec_insert(db_values)

我不清楚的表情和糟糕的英语可能会困扰别人:(