如果我想将多个对象插入SQL Server数据库,我似乎必须这样做:
all_raw_images = []
for content in itertools.islice(content,1,len(content)):
image_id = content.split()[0]
driver_id = content.split()[2]
camera_spec = content.split()[1] + content.split()[2]
image_spec = [image_id,driver_id,camera_spec]
image_folder_file = read_img_folders_file()[0]
cam_spec=read_img_folders_file()[1]
nb = read_img_folders_file()[2]
image_path=''
for i in range(nb-1):
if cam_spec[i]== image_spec[2]:
image_path=image_folder_file[i]+'/'
raw_image= image_path+str(image_id).zfill(10)+'.png'
all_raw_images.append(raw_image)
return (all_raw_images)
把它放在一起让我把头发拉出来,我有一张28个字段的桌子。我必须分别写出4个单独的长列表,只有最微不足道的差异(DB字段名称可能使用不同的命名约定)。这看起来很疯狂;是否有更短的方式?
实体框架对我来说不是一个选项,这将是我的第一选择,我必须推出代码。
答案 0 :(得分:3)
如果您完全反对使用外部库,那么这个怎么样?
void Insert (Dictionary <string, SqlType> cols, Object [] objects)
{
string colNames = string.Join (",", cols.Keys);
string paramNames = string.Join (",", cols.Keys.Select (c=>"@"+c));
using (var command = new SqlCommand(@"INSERT INTO Table1 (" + colNames +
") VALUES (" + paramNames + ")",conn))
{
foreach (var col in cols)
{
command.Params.Add("@" + col.Key, col.Value);
}
foreach(var o in objects)
{
// Here you would have to list them all unless
// your object o is a Dictionary<string, object> or a DataRow.
command.Params["@param1"].Value = o.Param1;
command.Params["@param2"].Value = o.Param2;
command.Params["@param3"].Value = o.Param3;
...
command.ExecuteNonQuery();
}
}
}