我正在使用带有表RESUME和列PageIndex的数据库,其类型是数据库中的数字但是当我想将此PageIndex值存储到整数时,我得到异常错误
指定的演员表无效。
这是代码
string sql;
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\\Deliverable4.accdb";
protected OleDbConnection rMSConnection;
protected OleDbDataAdapter rMSDataAdapter;
protected DataSet dataSet;
protected DataTable dataTable;
protected DataRow dataRow;
按钮上的单击
sql = "select PageIndex from RESUME";
rMSConnection = new OleDbConnection(conString);
rMSDataAdapter = new OleDbDataAdapter(sql, rMSConnection);
dataSet = new DataSet("pInDex");
rMSDataAdapter.Fill(dataSet, "RESUME");
dataTable = dataSet.Tables["RESUME"];
int pIndex = (INT)dataTable.Rows [0] [0];
rMSConnection.Close();
if (pIndex == 0)
{
Response.Redirect("Create Resume-1.aspx");
}
else if (pIndex == 1)
{
Response.Redirect("Create Resume-2.aspx");
}
else if (pIndex == 2)
{
Response.Redirect("Create Resume-3.aspx");
}
}
我在这一行收到错误
int pIndex = (int)dataTable.Rows[0][0];
答案 0 :(得分:2)
如果它无法将其转换为整数,则它不会从数据库中将其检索为整数。该字段的数据类型是什么?
尝试检查dataTable.Rows[0][0].GetType().ToString()
的结果,看看对象究竟是什么。
答案 1 :(得分:2)
你说“类型是数据库中的数字” - 它听起来好像这可能是numeric
,在这种情况下,.NET-land中最合适的匹配是{{1} }。如果您知道它是一个int,那么您可以随后将其从decimal
转换为decimal
:
int
答案 2 :(得分:0)
我解决了这个问题。
int pIndex = int.Parse(dataTable.Rows[0][0].ToString());
答案 3 :(得分:0)
我是否可以谦虚地建议采取不同的方式?:
string conString = "..."; // <-- your connection string
using (IDbConnection connection = new OleDbConnection(conString))
{ // ^^^ interface type makes your code less dependent on a particular backend!
connection.Open();
try
{
using (IDbCommand command = connection.CreateCommand())
{ // ^^^ ditto
command.CommandText = "SELECT PageIndex FROM RESUME";
object scalar = command.ExecuteScalar();
// ^ ExecuteScalar reads the first value in the first column
// of the result set; or returns null if it fails to do so.
if (scalar == null) throw ...; // unexpected result from database!
if (scalar == DBNull.Value) throw ...; // ditto!?
int pIndex = (int)scalar;
switch (pIndex)
{
case 0: Response.Redirect("Create Resume-1.aspx"); break;
case 1: Response.Redirect("Create Resume-2.aspx"); break;
case 2: Response.Redirect("Create Resume-3.aspx"); break;
default: throw ...; // unexpected result from database!?
}
}
}
finally
{
connection.Close(); // (will execute even when exceptions are thrown!)
}
}