C#如何不关闭SqlDataReader执行更新语句
publicvoidUpdateLevel(){SqlConnectioncon=newSqlConnection(connstring);con.Open();try{...
public void UpdateLevel()
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
try
{
string level = null;
string sql = string.Format("select OnlineDay,UserId from UserInfo");
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader reader = com.ExecuteReader();
int num2=0;
while (reader.Read())
{
int userId = Convert.ToInt32(reader["UserId"]);
double num = Convert.ToDouble(reader["OnLineday"]);
if (num < 5)
{
level = "-";
}
else if (num >= 5 && num < 32)
{
level = "☆";
}
else if (num >= 32 && num < 320)
{
level = "C";
}
else
{
level = "◎";
}
string sql2 = string.Format("update UserInfo set Level='{0}' where UserId={1}", level, userId);
SqlCommand com2 = new SqlCommand(sql2, con);
num2 = (int)com2.ExecuteNonQuery();
} reader.Close();
Console.WriteLine("更新成功!");
Console.WriteLine("本次共更新用户数:" + num2);
} 展开
{
SqlConnection con = new SqlConnection(connstring);
con.Open();
try
{
string level = null;
string sql = string.Format("select OnlineDay,UserId from UserInfo");
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader reader = com.ExecuteReader();
int num2=0;
while (reader.Read())
{
int userId = Convert.ToInt32(reader["UserId"]);
double num = Convert.ToDouble(reader["OnLineday"]);
if (num < 5)
{
level = "-";
}
else if (num >= 5 && num < 32)
{
level = "☆";
}
else if (num >= 32 && num < 320)
{
level = "C";
}
else
{
level = "◎";
}
string sql2 = string.Format("update UserInfo set Level='{0}' where UserId={1}", level, userId);
SqlCommand com2 = new SqlCommand(sql2, con);
num2 = (int)com2.ExecuteNonQuery();
} reader.Close();
Console.WriteLine("更新成功!");
Console.WriteLine("本次共更新用户数:" + num2);
} 展开
展开全部
不行地,SqlDataReader在遍历完之前会一直连接数据库,中间有任何数据库操作都会报错,你把得到的数据放DataTable里,然后再遍历,做你的更新操作就没问题了
string sql = string.Format("select OnlineDay,UserId from UserInfo");
SqlCommand com = new SqlCommand(sql, con);
sqldataadapter sda=new sqldataadapter(com);
DataTable dt=new DataTable();
sda.Fill(dt);
for(int i=0;i<=dt.rows.count.....
string sql = string.Format("select OnlineDay,UserId from UserInfo");
SqlCommand com = new SqlCommand(sql, con);
sqldataadapter sda=new sqldataadapter(com);
DataTable dt=new DataTable();
sda.Fill(dt);
for(int i=0;i<=dt.rows.count.....
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询