using (SqlConnection mySqlConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
SqlCommand myCommand = new SqlCommand("SelectCity", mySqlConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlParameter prmcountrycode = new SqlParameter("@countrycode", SqlDbType.NVarChar, 50);
prmcountrycode.Value = countrycode;
myCommand.Parameters.Add(prmcountrycode);
mySqlConnection.Open();
List<string> allcitiesnames = new List<string>();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
int count = myReader.FieldCount;
if (myReader.Read())
{
allcitiesnames.Add(myReader.GetString(myReader.GetOrdinal("CityName")));
}
else
{
mySqlConnection.Close();
InsertNewCity(countrycode);
}
myReader.Close();
}
mySqlConnection.Close();
}
答案 0 :(得分:2)
试试这个,
while(myReader.Read())
{
allcitiesnames.Add(myReader.GetString(myReader.GetOrdinal("CityName")));
}
答案 1 :(得分:1)
基本上SqlDataReader
旨在一次读取一个数据库行
更改
if (myReader.Read())
{
allcitiesnames.Add(myReader.GetString(myReader.GetOrdinal("CityName")));
}
else
{
mySqlConnection.Close();
InsertNewCity(countrycode);
}
到
while(myReader.Read())
{
if (myReader.Read())
{
allcitiesnames.Add(myReader.GetString(myReader.GetOrdinal("CityName")));
}
else
{
mySqlConnection.Close();
InsertNewCity(countrycode);
}
}
<强>更新强>
而不是两次调用数据库我建议你改变你的程序
create procedure SelectCity
@countrycode nvarchar(50)
as
begin
if exists(select top 1 CountryCode from mytable where CountryCode=@countrycode)
begin
select * from mytable
end
else
begin
insert into mytable (CountryCode)
values (@countryCode)
end
end
所以这将选择all if if else将其插入表中
将SqlDataReader
与ExecuteReader
答案 2 :(得分:1)
如果您想直接使用所有行,则必须使用SqlDataAdapter
并使用DataTable
将其填入数据库中的数据并从中返回DataTable
。
SqlDataReader
以一定的方式逐行获取行,请参阅here how to use SqlDataAdapter,另见MSDN article
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
// 1
// Open connection
using (SqlConnection c = new SqlConnection("Connection string here"))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlDataAdapter a = new SqlDataAdapter("Query Here", c))
{
// 3
// Fill DataTable with data
a.Fill(t);
}
}