DataAdapter.Fill方法执行sql有语法错误表不存在
2023-03-22 本文已影响0人
吉凶以情迁
使用DataAdapter对象填充DataTable时,如果所请求的表不存在,不会抛出异常。相反,它只是返回一个空的DataTable。这是因为DataAdapter.Fill()方法的设计思想是尽可能的填充数据,即使在遇到错误或异常时也应该尽量填充尽可能多的数据。因此,如果您需要确保表存在,请在填充数据之前检查表是否存在,或者在查询中包含适当的错误处理代码以处理表不存在的情况。
原创方法
if (poDataTable.Columns.Count < 1)
{
_sMessage = "执行Fill语句出现错误,可能表不存在,或语法出现错误";
}
if (poDataTable.Columns.Count == 1 && poDataTable.Columns[0].ColumnName.Equals("Column1") && poDataTable.Rows.Count <= 0)
{
_sMessage = _sMessage + "执行Fill语句出现错误,可能表不存在,或语法出现错误";
}
其它方法实现
但是这个方法我测试并不会触发
adapter.FillError += new FillErrorEventHandler(FillError);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "ThisTable");
protected static void FillError(object sender, FillErrorEventArgs args)
{
if (args.Errors.GetType() == typeof(System.OverflowException))
{
// Code to handle precision loss.
//Add a row to table using the values from the first two columns.
DataRow myRow = args.DataTable.Rows.Add(new object[]
{args.Values[0], args.Values[1], DBNull.Value});
//Set the RowError containing the value for the third column.
myRow.RowError =
"OverflowException Encountered. Value from data source: " +
args.Values[2];
args.Continue = true;
}
}