-1

So I have a value in a database which I want to get and then subtract another value which is gotten from the users input and re-write this new value in the place of the value which was previously in the database. I heard this can be done with a prepared statement not too sure.

Thanks.

  • 1
    Yes it can. What have you tried so far? – Darwin von Corax Apr 07 '16 at 03:46
  • Welcome to StackOverflow. Please visit the [help], take the [tour] and read [ask]. Your question reads like "I'm too lazy to look this up on my own and maybe I can get someone to write it for me", and as such is off-topic. If you try it and can't get it to work, then you can post what you've done along with the error messages and/or unexpected behavior and we'll try to help you. But first you have to make an effort yourself. – Jim Garrison Apr 07 '16 at 03:56
  • not really sure how to use a prepared statement. I've Done it the long way by reading the value in the database and then subtracting my value then re-writing. but i'm trying to cut down code with a prepared statement. – Pedro Lozano Apr 07 '16 at 03:57
  • Duplicate of http://stackoverflow.com/q/3580641/18157 – Jim Garrison Apr 07 '16 at 04:09

2 Answers2

0

If the statement is going to be reused often, you can avoid processing time spent by the database parsing the SQL statement for each call by creating a prepared statement and updating on the value for each call -- the prepared statement will have a placeholder for the variable value, and the SQL will be parsed only when creating the prepared statement.

stm = conn.prepareStatement("update MyTable set Col1 = Col1 - ? where KeyCol = ?");

Then each time you have a new key value and associated offset, you set them as follows:

stm.setInteger(1,newOffset);  // assign newOffset value to first ?
stm.setInteger(2,keyVal);
stm.execute();  // executes the statement with the specified values
dr.java
  • 46
  • 5
0

We need to know what your tables and attributes are. If it was something like a table called users where each user has a certain number of points, you could do an SQL statement like this:

SELECT points FROM users WHERE username='somename';

You could then update that score with your new points variable "newpoints" by doing something like this:

UPDATE users SET points = newpoints WHERE username = 'somename';

This site has a few really useful commands: http://g2pc1.bu.edu/~qzpeng/manual/MySQL%20Commands.htm