jdbc code to update informations in a mysql table - java

i have a code in java-eclipse to update the informations in a table with mysql but the values in selected row of the table didnt update after running this function.for example i want to replace value "b" inested of "a" in column "username" please help me :(
a is first value
b is value that i want to replace with a
username is name of the one column
my code:
public void Change("username","a","b") throws SQLException{
prs=connect.prepareStatement( "UPDATE user0 SET " +s1+ "='" +s3+ "' WHERE '" +s1+ "'='" + s2+"'");
prs.execute();
}// end of function change

That shouldn't even compile, your syntax is wrong:
public void Change(String username, String a, String b) throws SQLException{...}

I think you are having trouble with all that quotation. It's better to use what PreparedStatement has to offer, for example:
prs = connect.prepareStatement("UPDATE Users SET UserName = ? WHERE IDUser = ?");
prs.setString(1, "some String");
prs.setInt(2, 145);
prs.execute();
Probably with that you'll be able to fix your problem.

I hope that is not an exact excerpt of your code. If it is, then you should change the prototype part to
void Change(String s3, String s1, String s2) throws SQLException
Now, the code itself is prone to SQL injection.
Seeing as you are using a PreparedStatement, you should first declare it:
PreparedStatement prs;
Afterwards, you should set the parameters according to their type. See how to use PreparedStatement here: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html .
Last but not least, please try to format the code you enter in a question. Good luck! :)
Later edit: you should also use executeUpdate() instead of execute(). It will return an integer corresponding to the number of rows that were updated. You can then write that number in the console to see if your update went ok. Remember that executeUpdate() is for UPDATE, INSERT and DELETE only :)

Related

Is this Database UPDATE command with calculation correct?

I want to set the ArtikelAnzahl (the number of article) in the database to the term, which I will get from my Java GUI.
So the SQL command string should look like:
"update warenliste set Anzahl=Anzahl+"anzahl"where Artikel_ID="+arikel_ID;
where:
warenliste is the table and Anzahl is a comlum which should get updated.
the number of article in the DB should be added to the number which we will get from the GUI.
Is this command right? I just learned SQL yesterday and unfortunately am not yet good at it.
public void setArtikelAnzahl(int anzahl, int arikel_ID) {
try {
String query = "update warenliste set Anzahl=Anzahl+"anzahl"where Artikel_ID="+arikel_ID;
rs= st.executeQuery(query);
}
catch(Exception e) {
System.out.println(e);
}
}
The SQL part
The SQL part of the query seems fine if artikel_id and anzahl are both numeric (and that it's anzahl and not artikeanzahl).
Let's instantiate the statement for an imaginary article 1 and a quantity of 27:
update warenliste set Anzahl=Anzahl+27 where Artikel_ID=1;
If you test this here with the following schema, it will work out fine:
create table warenliste (artikel_ID numeric,
bezeichnung varchar(100),
anzahl numeric);
insert into warenliste values (1,"Schraubenzieher", 1050);
insert into warenliste values (2,"Hammer", 10347);
The Java part
But there are a couple of problems in the Java part. First, you need to correct the statement to make the Java code compile. You also need to add missing spaces in the result string:
String query = "update warenliste set Anzahl=Anzahl+"+anzahl+" where Artikel_ID="+arikel_ID;
^ ^ ^
Since you're not too familiar with SQL yet, I'd suggest to display the query string before you execute it. Just to verify that it matches your expectations.
Now if ariktel_id is a string, and not a numeric, you may have to add the missing quotes around in the query string around the variable.
It's not required, but I'd recommend that when you build the query string, you use uppercases in the SQL statements. This will facilitate reading the java code, especially when you'll have SQL strings mixed with java variables like here.

Lookup and extract db value based on input (Java & SQL Server)

New to java.
I am attempting to write a class that will input a username, run a query on the username to find the ID, and subsequently use that ID in "where clauses" on all my other classes.
This is the statement that I execute (which will only ever return a recordset of a single row):
String sqlStatement = "SELECT AccountHolderId, Passcode from CIS4720.DBO.AccountHolder " +
"where Username = '" + logonName + "'";
Here is my attempt at extracting the ID via the username...
while (rset.next())
{
if(rset.getInt("Username")==logonName){
int whosOnFirst = rset.getInt("AccountHolderId");
}
I saw another answer on the forum that says you can't assign database values to variables. If that is the case, what is a better strategy?
(Also, I realize I'm not parameterizing, but I'd like to get this working before fixing that issue. This is for a course assignment so I am not worried about hack attacks).
P. S. Thanks I fixed the double equals sign (and the extra parenthesis) in the code above.
Here are some comments about the code:
rset.getInt("Username") will get the column Username from the result but it also looks for an Integer column because of getInt. You are not selecting that column in the sql statement so will error out.
If you select it and get a string, use .equals() instead of == to compare string. Also, one = is assignment and == is comparison.
You can use getString to read Strings from the result set.
You don't need to check the username and match it since your query should return exactly that user's data so I would remove the if condition entirely and just have the getInt line there.

Mysql query in with the answer true, false

I was not too long ago studying java, so maybe I have a stupid question.
I have a table, where i store some info.
And i want to check in this table on availability of some information (it will be only one line), and if yes - take from this line, the information in a particular column, if no - do another thing.
I really don`t know how to do this.
My idea was something like this: at first - check the table:
SELECT * FROM tablename WHERE nickname = "kvant";
then if true, do another query with searching info.
and do this with condition if\else. but all my attempts not turn.
I hope for your help, sorry for my awry English.
Check if the data exists like this:
IF EXISTS(SELECT * FROM tablename WHERE nickname = "kvant")
BEGIN
--value is found so go ahead
END
ELSE
--value not found
BEGIN
END
One simple way is to query the database and get the result. If result!=Null {//do something} else {//Do something}
(Can use try - catch as well)
Pure java possible solution:
Try to get that value in the query. Get the ResultSet rs of that query and:
if(rs.next()) {
String value = rs.getString("value"); //Assuming the column is value and that it is a String.
//Do whatever you want with the value
} else {
//The other thing
}
If you can not take the value from the first ResultSet, do another query in the if.
write in sql like select case exists (select * from yourtable where condition) then 'dothis thing' else 'dootherthing' from 'yourtable' where 'yourcondition'
since you wanted to run some other query after you know you have some conditon exists.

how to replace a string value in java

i replace a particular string in a statement like the following
SQL = SQL.replaceAll("CUSTOMER_NUMBER", customer);
this conversion goes as integer but i want to replace this as a string like the following
AND CIMtrek_accountlist_customer_number = '0002538'
but at present it replaces like the following
AND CIMtrek_accountlist_customer_number = 0002538
how to do this in java.
Just get it to output the ' as well as the customer variable
SQL = SQL.replaceAll("CUSTOMER_NUMBER", "'" + customer + "'");
However as #jlordo mentioned in a comment, you should look at using prepared statements which will allow you to inject values into a prepared sql statement.
Though you should be using PreparedStatement if you are running SQL, However if placeholder "CUSTOMER_NUMBER" is under your control, It is better to use String.format. See and example here

Is it possible to store and retrieve a boolean value in a varchar field using Java JDBC?

quick question: my customer has a situation where he has his database with a varchar field and the corresponding jdbc code is storing/retrieving a boolean.
I guess that the boolean values false and true are going to be translated to "0" and "1" but I would like to have a confirmation of this (I can't find the precise behavior specification online, maybe it depends on each driver, Oracle in this case).
I know I could experiment by myself, but I want to have a try at stackoverflow.com!
Thanks for your answer,
Eric.
I agree with the answer that the semantics are highly database specific, which is why I think the important answer is that you shouldn't do this. A change in JDBC driver or something similar could cause the implicit behaviour to break.
Instead, If using raw JDBC, have the code take the boolean and convert it to an appropriate String ('true' or 'false' are obvious choices) and then set this value to the VARCHAR column. On read from the VARCHAR column do the reverse, throwing or handling the exception case where the String is not one of the boolean values as expected.
It works with MySQL, the table holds 0 for false and 1 for true.
The output:
123 => true
456 => false
The source code:
package com.lurz.jdbc;
import java.sql.*;
// Test using Varchar for Boolean
public class BoolTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/booltest", "booltest", "booltest");
conn.prepareStatement("create table booltest (id bigint, truefalse varchar(10));").execute();
PreparedStatement stmt = conn.prepareStatement("insert into booltest (id, truefalse) values (?, ?);");
stmt.setLong(1, (long)123);
stmt.setBoolean(2, true);
stmt.execute();
stmt.setLong(1, (long)456);
stmt.setBoolean(2, false);
stmt.execute();
ResultSet rs = conn.createStatement().executeQuery("select id, truefalse from booltest");
while (rs.next()) {
System.out.println(rs.getLong(1)+ " => " + rs.getBoolean(2));
}
}
}
Thanks for all your answers,
After a bit of experimentation I saw that Oracle was indeed using the values 0 and 1 to store boolean values in varchar2 columns without any mapping in the JDBC code.
That said, if I can give a bit of context, we're going to fix that situation where things would just work "by accident". I just wanted to know if, in the meantime, the application would blow up.
And, as I said, I wanted to see how effective the stackoverflow community was after having listened to the Joel/Jeff podcasts since the beginning!
It is indeed effective!
Unfortunately, BOOLEAN semantics are highly database-specific. I'm guessing that the Oracle driver is going to translate boolean values to a VARCHAR field into "true" and "false", rather than 0 and 1, but you should verify this yourself.
It is possible to use VARCHAR(2) for representing a Java Boolean in Oracle. However, I would advise against it and suggest you use a NUMBER(1) instead. If the Boolean column has an index on it and you use it in a WHERE clause Oracle will apply the to_number numeric function on it to turn the "0" into a 0 or the "1" into a 1. Application of that function negates the use of the index on that column and will cause you to incur a full table scan.

Categories

Resources