mysqldb simple question (find unique number)

Steve Holden sholden at holdenweb.com
Wed Apr 25 15:49:41 EDT 2001


"Jacek Pop³awski" <jp at ulgo.koti.com.pl> wrote in message
news:slrn9eckbh.2f7.jp at localhost.localdomain...
> id_producenta is primary key (int) for table producent
> I need to find unique value for it, I use that code:
>
>     dbh.query('select id_producenta from producent');
>     res=dbh.store_result()
>     how=res.num_rows();
>     id=[]
>     for i in range(how):
>       r=res.fetch_row()
>       id=id+[int(r[0][0])]
>     del res
>     return max(id)+1;
>
> Looks quite long... how to write it in better way?
>
MySQL implements the max() SQL function.

Your current code has your database client program scanning all rows to find
the maximum value. Try something along the lines of (untested):

dbh.query('select max(id_producenta) from producent')
res = dbh.store_result() # should only be one row!
m = int(res.fetch_row()[0])
return m+1

Of course, you will realise that problems might arise should any two users
concurrently try to use any such routine, since NySQL (as far as I remember)
does not support transactions.

regards
 steVe





More information about the Python-list mailing list