我遇到这种情况,我创建了一个在数据库中插入行的方法。我向该方法提供了列,值和表名。
COLUMNS = [['NAME','SURNAME','年龄'],['SURNAME','NAME','年龄']] VALUES = [['John','Doe',56],['Doe','John',56]]
TABLE ='people'
这是我想通过的方式,但它不起作用:
compile 'com.google.api-client:google-api-client-android:1.20.0' exclude module: 'httpclient'
compile 'com.google.http-client:google-http-client-gson:1.20.0' exclude module: 'httpclient'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
Call<UserMaster> call = Retro.getRetroWS().UserLogin(userMaster, otp);
try {
Response<UserMaster> response = call.execute();
if (response.isSuccessful()) {
return response.body();
} else return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
这是它将如何通过查询,但问题是我必须有预定义的列名,这不好,因为如果其他列表有不同的列排序怎么办?姓名将以姓氏和姓氏为名。
db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = "insert into %s (?) VALUES(?)" % TABLE
cursor.executemany([sql,[COLUMNS[0],VALUES[0]],[COLUMNS[1],VALUES[1]]])
db.commit()
我希望我能够清楚地解释清楚。 PS。 COLUMNS和VALUES是从json词典中提取的
[{ 'NAME': '约翰', 'SURNAME': 'Doe的', '年龄':56 ...},{ 'SURNAME': 'Doe的', 'NAME': '约翰','AGE “:77 ...}]
如果有帮助的话。
SOLUTION:
db = DB_CONN.MSSQL() #method for connecting to MS SQL or ORACLE etc.
cursor = db.cursor()
sql = 'insert into %s (NAME,SURNAME,AGE) VALUES (?,?,?)'
cursor.executemany(sql,[['John','Doe',56],['Doe','John',56]])
db.commit()
答案 0 :(得分:2)
您可以利用python词典的键值对列表的非随机性。
您应该检查json
记录数组中的所有项目是否都有相同的字段,否则您将在查询中遇到异常。
columns = ','.join(records[0].keys())
sql = 'insert into %s (%s) VALUES (?,?,?)' % (TABLE, columns)
cursor.executemany(sql,[record.values() for record in records])