[Tutor] Some help Please

Evert Rol evert.rol at gmail.com
Wed Feb 15 16:42:45 CET 2012


  Hi Joseph,

> take an example of updating Bank Accounts,
> gaving the following table:
> 
> acc_id		acc_name	    standing_Balance
> mn0001		computer	     20000
> 
> my problem is how can i credit the standing balance from user data,as
> in making a deposit onto the computer account, using the code below:-
> 
> 
> 
> import MySQLdb as mdb
> import sys
> 
> con = mdb.connect('localhost', 'joseph', 'jmm20600', 'savings');
> 
> dep = input('Enter Amount: ')
> 
>            cur.execute("UPDATE accounts SET Standing_Amount =
> (Standing_Amount + dep) WHERE Acc_ID = 'MN0001'")
> 
> 	    conn.commit()
> 
> HOw do i format "dep" in order to be added onto the standing_Amount,to
> make an increment?

First of all, what have you tried? And what problems or errors are you getting?
Then people on the list know better how to reply, and what details you may need to know.
For example, the above code is not code that will run: the cur and conn variables are undefined, and the indentation appears to be messed up. So it would appear you have not tried things out yet.

If I understand your question correctly, however, it is probably fairly straightforward: you need to replace the 'dep' variable inside the string with a %-sequence, and add the dep inside a tuple as the second argument of the execute statement.
An example is probably better:

cur.execute("UPDATE accounts SET Standing_Amount = (Standing_Amount + %s) WHERE Acc_ID = 'MN0001'", (dep,))

That will take the value of the variable dep and put it at the %s. Note that trailing ',', to make the second argument a tuple.
Note that you may want to first validate that dep is actually a number, not some string like "a lot of money"…

But, in fact, this should all be reasonably clear with the help of the MySQLdb documentation. From a quick search, I can find: http://mysql-python.sourceforge.net/MySQLdb.html#some-examples , which explains the above.
For some other details, there is the Python DB API description: http://www.python.org/dev/peps/pep-0249/


  Evert


> Please, is it the same thing with the withdrawing format, in case i
> want to decrement the account as in withdrawing??
> 
> 
> joseph



More information about the Tutor mailing list