update mysql database with jdbc - mysql

I have an error updating my database because of variables. This is my code:
UPDATE `payment` SET `paid`=1 AND `amoun`=$amountpaid WHERE `paid`=0 AND `userid`=$uid
$amountpaid is the amount of the bill that the user paid and $uid is user id. It seems like using $ in front of variable names is forbidden. How can I use variables in SQL?

Where are your variables coming from? You probably want something like this if you're using JDBC:
int setPaid = 1;
int amountPaid = x; // put $amountpaid here
int wherePaid = 0;
int userId = y; // put $uid here
String updateQuery = "UPDATE payment SET paid = ?, amoun = ?"
+ " WHERE paid = ? AND userid = ?";
PreparedStatement ps = con.prepareStatement(updateQuery);
ps.setInt(1, setPaid);
ps.setInt(2, amountPaid);
ps.setInt(3, wherePaid);
ps.setInt(4, userId);
ps.executeUpdate();

I got the solution by using String.
I converted the ArrayList to a String and then sent the data as string. The data got updated but I don't know what will happen next if I want to view the data in the client tier...

Related

Using JDBC template, How can I update a column in every customer in a mysql database?

So, I am trying to create a function that when called updates the lastEmailed column for every customer in the database called customers, but I can't seem to find out an approach that seems to work. Any help would be greatly appreciated! Also, the input style is in the format 2014-12-09 14:20:47 (datetime). ** this is a NamedParameterJdbcTemplate.
public void updateTime(String timeSent){
// String query = "UPDATE customers SET lastEmailed ='" + timeSent+"'";
// String query = "UPDATE customers SET lastEmailed = ?";
// String query = "INSERT INTO CUSTOMERS "
// this.jdbcTemplate.
// this.jdbcTemplate.execute(query);
// this.jdbcTemplate.update
// SqlParameterSource [] parameterSource = SqlParameterSourceUtils.createBatch(this.getCustomerList().toArray());
// this.jdbcTemplate.batchUpdate("INSERT INTO CUSTOMERS (id,lastEmailed) VALUES (:customerNumber, " +timeSent + ")", parameterSource);

MySQL Jdbc convert string to date

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// date here is a string of format yyyy-MM-dd
java.util.Date date_1 = df.parse(date) ;
java.sql.Date sqldate = new java.sql.Date(date_1.getTime());
sql = "select * from fgs_stock_report where Report_date = ? ";
PreparedStatement two = con.prepareStatement(sql);
two.setDate(1,sqldate);ResultSet rs ;
rs = two.executeQuery(sql) ;
Here I get a Java Sql Exception asking for the right syntax near? . I am a beginner and I searched a lot for a solution but couldnt find. Please help me.
I think I see the problem, you are using a Statement.executeQuery(String) but you want PreparedStatement.executeQuery() - that is.
PreparedStatement two = con.prepareStatement(sql); // <-- Prepare a Statement.
two.setDate(1,sqldate); // <-- bind the parameter.
ResultSet rs ;
rs = two.executeQuery(sql) ; // <-- throw it away and use raw sql
What you want is,
ResultSet rs = two.executeQuery(); // <-- I'd use one line

Use C variable in Mysql

I'm trying to pass a variable into Mysql in C.
Could someone tell me what's going wrong here:
char request[100];
int id = 1;
snprintf(request, 100, "UPDATE database SET x = 1 WHERE id = %d", id);
mysql_query(&mysql, request);
Thank you.
EDIT:
I assume there is a problem with snprintf because this also doesn't
work:
snprintf(request, 100, "UPDATE database SET x = 1 WHERE id = %d", id);
mysql_query(&mysql, "UPDATE database SET x = 1 WHERE id = 1");
But without this snprintf line, code works
Thanks #Claris
Solution:
static char request[100] = {0};
int id = 1;
snprintf(request, 100, "UPDATE database SET x = 1 WHERE id = %d", id);
mysql_query(&mysql, request);

SQL Insert/Update does fails, does not invoke errors

Afternoon everyone,
I'm currently trying to insert or update form field values via params into a mysql after some simple validation. The form submits, but does not actually execute any of the operations and does not raise a syntax or database connection error. I know my connection string works because I fetched values from it to compare to in the code prior to the nested evaluation blocks shown below. The foreach loops were inserted as an alternate means of validating that the values have indeed been altered in the table. Your help is greatly appreciated, as always:
my $dbusr = param("dbuser");
my $dbpw = param("dbpass");
my $dbmail = param("dbemail");
my $dbtel = param("dbphone");
my $postflag = param("Submit");
if ($dbusr ne "") {
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
warn( $DBI::errstr ) if ( $DBI::err );
my #results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$loopval = 1;
}
}
unless($loopval){
$sth = $dbh->prepare("INSERT INTO USER
(username, password, phone, email)
values
(?,?,?,?)");
$sth->execute($dbusr, $dbpw, $dbtel, $dbmail);
warn( $DBI::errstr ) if ( $DBI::err );
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
#results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$successflag = 1;
}
}
}
else{
$sth = $dbh->prepare("UPDATE USER
SET (password = ?, phone = ?, email = ?)
WHERE username = ?");
$sth->execute($dbpw, $dbtel, $dbmail, $dbusr);
warn( $DBI::errstr ) if ( $DBI::err );
$sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
$sth->execute('$dbusr');
#results = $sth->fetchall_arrayref();
foreach(#results){
if ($dbusr eq $_){
$successflag = 1;
}
}
}
}
Basic Perl: '-quoted strings do NOT interpolate variables:
$sth->execute('$dbusr');
^-- ^---
You're literally passing $, d, b, etc... to your query as the placeholder value.
Try
$sth->execute($dbusr); // note the lack of ' quotes
instead.
You are searching for entire rows with the SELECT * FROM USER WHERE username LIKE ? statement, and are then fetching all the rows in one go with
my #results = $sth->fetchall_arrayref();
That method "returns a reference to an array that contains one reference per row.", but you are treating the returned value as an list of usernames:
foreach(#results){
if ($dbusr eq $_){
$loopval = 1;
}
}
To make this work you should just fetch the username column, and treat the returned rows as references of references. And as you look for exact matches in the database replace LIKE with =:
$sth = $dbh->prepare("SELECT username FROM USER WHERE username = ?");
$sth->execute($dbusr); # no quoting
die( $DBI::errstr ) if ( $DBI::err ); # what else to do if the execute fails?
my $results = $sth->fetchall_arrayref(); # an arrayref is returned
foreach(#$results){ # de-reference the array
if ($dbusr eq $_->[0]){ # each row is an arrayref, look in first element
$loopval = 1;
}
}
(Of course the same applies to the second search.)

Servlets/JSP - Unable to access database on SOAP webservice

I am trying to create a simple little webservice on a glassfish server backed by a mysql server on my netbeans
Its designed to be a very simple currency conversion service
Here is what its supposed to do
It takes an amount of money (Always in GBp) as an INT and a currency to convert it in as a string.
The service then looks up that currency from my database table to get the conversion rate with a query like
select * from exchange.rates where currency = string
Then it performs the simple calculation to convert the money into the currency and returns the amount
The problem is that i have no clue how to call that conversion rate from my mysql server, i tried and tried but nothing happens
i just keep getting the same amount i entered in.
I tried entering euro and 10
I set the rate for that in my database but i just got 10 back out when i tested the webservice
/**
* Web service operation
*/
#WebMethod(operationName = "convert")
public int convert(#WebParam(name = "currency") String currency, #WebParam(name = "amount") int amount) {
int newamount = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/exhange",
"root", "25587");
PreparedStatement st =
con.prepareStatement("select * from rates where currency = '" + currency+"'");
ResultSet rs = null;
rs = st.executeQuery();
rs.first();
newamount =rs.getInt("conversion") * amount;
return newamount;
} catch (Exception e) {
System.out.println("error");
}
return amount;
}
Whe you use prepared statemen you need to pass the parameter explicitly:
PreparedStatement st = con.prepareStatement("select * from rates where currency = ?");
st.setString(1,currency) //Check this
ResultSet rs = st.executeQuery();
// If you are sure that is only one row then you nee to do
String columnX = null;
if (rs.next() != null) {
columnX = rs.getString(1); //Where 1 is the first column
}