简体   繁体   中英

Is it possible to use a loop for this type of query set?

sc = new MySqlCommand("Update tbName set AvgTime=" + avgTimeArray[1]+ " where   PatternId=1", msc);
                sc.ExecuteNonQuery();

sc = new MySqlCommand("Update tbName set AvgTime=" + avgTimeArray[2]+ " where   PatternId=2", msc);
                sc.ExecuteNonQuery();

sc = new MySqlCommand("Update tbName set AvgTime=" + avgTimeArray[3]+ " where   PatternId=3", msc);
                sc.ExecuteNonQuery();

Is it possible to use a loop for this type of query set? If it is possble how to do it? ( avgtImeArray is a array)

for(int i = 1; i < avgTimeArray.length; i++){
sc = new     MySqlCommand("Update tbName set AvgTime = @AvgTime where PatternId = @PatternID", msc);
sc.Parameters.Add(new ObjectParameter("AvgTime", avgTimeArray[i].ToString())); 
sc.Parameters.Add(new ObjectParameter("PatternID", i.ToString())); 
sc.ExecuteNonQuery();}

This will work around your potential SQL injection vulnerability. Note, code is untested. Answer based on Tinman7757's posted answer and tweaked as needed...

MSDN article on Parameterizing queries: https://msdn.microsoft.com/en-us/library/vstudio/Bb738521(v=VS.100).aspx . The problem with not parameterizing is it leaves the code open for someone with malicious intents to execute arbitrary SQL code (including but not limited to deletions and full blown table drops). You will want to obviously prevent this wherever possible.

Yes you can try something like:

  dim x as integer = 1
  Do
     dim MyAVG as Integer = avgTimeArray[x]
     sc = new MySqlCommand("Update tbName set AvgTime=" + MyAvg + " where PatternId=" + x, msc);
     sc.ExecuteNonQuery();
     x += 1
     if x > 3: exit do
  Loop
for(int i = 0; i < avgTimeArray.length; i++){
sc = new     MySqlCommand("Update tbName set AvgTime=" +  
avgTimeArray[i]+ " where   PatternId=" + i, msc);
sc.ExecuteNonQuery();}

Like Tim Schmelter said use a loop. 'i' represents the index of the array comparable to arrayAtIndex[0],arrayAtIndex[1]. instead put it in a loop with a using statment wrapped around it. and use arrayAtIndex[i]

If you need to start from a higher index use int i = 1

Hope this has some value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM