我有一个名为“产品”的表。我想检索所有条目的所有ID并将它们存储在一个数组中。
conn = new OleDbConnection();
conn.ConnectionString = "myconnectionstring";
conn.Open();
query = "SELECT * from Products";
cmd = new OleDbCommand(query,conn);
reader = cmd.ExecuteReader();
//Int16 a=(int)cmd.ExecuteScalar();
Int16[] id = { 0 };
int counter = 0;
while (reader.Read())
{
counter++;
id[counter] = reader.GetInt16(0); //I got error here that aray is out of bount
}
foreach (Int16 a in id)
{
Console.WriteLine(a);
}
conn.Close();
return id;
我已经更改了我的代码...它会抛出异常。比如说指定的强制转换是无效的。
conn = new OleDbConnection();
conn.ConnectionString = "my connetion string";
conn.Open();
query = "SELECT ID from Products";
cmd = new OleDbCommand(query,conn);
reader = cmd.ExecuteReader();
//Int16 a=(int)cmd.ExecuteScalar();
List<Int16> id = new List<Int16>();
while (reader.Read())
{
id.Add(reader.GetInt16(0));
}
conn.Close();
return id;
答案 0 :(得分:1)
你的id数组只有1个元素长。改为使用列表。
http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
List<int16> id = new List<int16>();
在你的while循环中:
id.Add(reader.GetInt16(0));
答案 1 :(得分:1)
您的数组ID是长度1.您应该重写一下以使事情变得更加动态。
尝试使用List而不是数组。这会让事情变得更加清洁。
答案 2 :(得分:0)
您已将数组声明为大小为1:
Int16 [] id = {0};
所以,当你试图去阵列中不存在的地方时,它会爆炸:
id [counter](除非counter = 0,你的麻烦)
而是尝试使用List:
列表ID =新列表();
以下是一些应该非常接近的快速代码:
conn = new OleDbConnection();
conn.ConnectionString = "myconnectionstring";
conn.Open();
query = "SELECT * from Products";
cmd = new OleDbCommand(query, conn);
reader = cmd.ExecuteReader();
//Int16 a=(int)cmd.ExecuteScalar();
List<Int16> id = new List<Int16>();
int counter = 0;
while (reader.Read())
{
counter++;
id.Add(reader.GetInt16(0));
}
foreach (Int16 a in id)
{
Console.WriteLine(a);
}
conn.Close();
return id.ToArray();
答案 3 :(得分:0)
我的问题解决了。实际上,我检索的数据类型为 int32 。我只需将 int16更改为int32。
conn = new OleDbConnection();
conn.ConnectionString = "my connetion string";
conn.Open();
query = "SELECT ID from Products";
cmd = new OleDbCommand(query,conn);
reader = cmd.ExecuteReader();
//Int16 a=(int)cmd.ExecuteScalar();
List<Int32> id = new List<Int32>();
while (reader.Read())
{
id.Add(reader.GetInt32(0));
}
conn.Close();
return id;