Shape 屬性可能因模具變更與資料庫不一致,以資料庫 Schema 為基準構建 SQL,確保欄位對應正確。
private DataTable GetReaderSchema(string tableName)
{
DataTable schemaTable = null;
string sql = string.Format("select * from [{0}]", tableName);
Database db = DatabaseFactory.CreateDatabase();
using (DbConnection conn = db.CreateConnection())
{
conn.Open();
DbCommand cmd = db.GetSqlStringCommand(sql);
cmd.Connection = conn;
using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly))
{
schemaTable = reader.GetSchemaTable();
}
}
return schemaTable;
}
// 提取欄位名稱清單
DataTable schemaTable = GetReaderSchema(tableName);
List<string> nameList = new List<string>();
foreach (DataRow dr in schemaTable.Rows)
nameList.Add(dr["ColumnName"].ToString());
string sqlValues = "";
foreach (string colName in nameList)
{
string value = VisioUtility.GetShapeCellValue(shape, colName);
if (!string.IsNullOrEmpty(value))
sqlValues += string.Format("'{0}',", value);
else
sqlValues += "NULL,";
}
// 移除尾隨逗號,組合完整 INSERT
string insertSql = string.Format("INSERT INTO [{0}] ({1}) VALUES ({2})",
tableName, string.Join(",", nameList), sqlValues.TrimEnd(','));
DeviceTableInfo)