c# - Insert query inside for loop not working correctly -


i working on asp .net project. have page generating random coupon keys. user enters quantity , generate.

so did, put loop according quantity , inside loop created random key , search key in db (key unique) , insert data in db.

code:

for (int = 0; < quantity; i++) {     {     couponkey = generatekey();    } while (!searchepinkey(couponkey));     conn = new sqlconnection(connstring);    conn.open();     using (sqlcommand cmd = new sqlcommand())    {        cmd.connection = conn;        cmd.commandtype = commandtype.text;        string query = "insert couponstock (coupon_key,  status, created_on)";        query += "values('" + couponkey + "','unused', getdate())";        cmd.commandtext = query;         cmd.executenonquery();      }     conn.close(); } 

inside loop, flow like:

-genrate random key -search if random key exists or not in db -if found similar again generate random key -insert data in db 

so when run page smaller quantities 10 or 15, working fine. when go 50 or 100 inserting random number of rows sometime 24, sometime 48. , application hangs after this. thinking sql server hitting numerous time in short interval. guidance on how handle helpful.

the reason find because of this

do {   couponkey = generatekey(); } while (!searchepinkey(epinkey)); 

if using couponkey in insert query, why use searchepinkey(epinkey)? searching couponkey in db?

you assigned generatekey() couponkey variable, , checking against epinkey, believe when epinkey stored in db hangs (an infinite loop), because epinkey same if assing new value couponkey

just change line

} while (!searchepinkey(epinkey)); 

to this

} while (!searchepinkey(couponkey)); 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -