Mysql query in with the answer true, false - java

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.

Related

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.

Checking for existing record in the SQL database

i have made a car rental management system in JAVA and SQL. The data base is working fine with no problems. i am stuck at checking if the data already exists in the database? like if a person enters NIC of 355353553.. it shouldn't be entered again.. Any suggestions about what i should do? thanks for any help!
You can set unique columns in mysql:
CREATE TABLE Cars
(
car_id int NOT NULL,
NIC int NOT NULL,
...
...
....
UNIQUE (car_id, NIC)
)
for more info, have a look here: Unique - sql syntax
Since you already have the database set to be unique, it sounds like you just want a method for handling errors in this case. I would use something like this personally, however I would bet that there is a more effective solution.
Create a method to get the count of the results from a query. In my example, I just called it countMethod. Have it return the number of rows from the query. You could alternatively use COUNT(*) from MySQL if you want to avoid using the java code. Here is some sudo code to get you started if you decided to try to implement.
int total = countMethod("SELECT id FROM the_table WHERE id=" + inputID);
if(total > 0) {
//Throw a warning message, it already exists
} else {
//Insert it into the database
}

How can I check if a unique value is already in a MySQL table from jFrame?

I have this on a jFrame Button:
label.setVisibility(false);
ResultSet rs = state.executeQuery("SELECT Str_Column FROM Table WHERE Str_Column = '"+ jTextField.getText() +"'");
//check for the existance
if(rs.getString("Str_Column").equals(jTextField.getText())){
label.setVisibility(true);
}
else{
new frameForSucceedInput.setVisibility(true);
}
if the if-case goes true or not always displays the succeed window and thats what i don't want to happen, it tells something about ResultSet null cause conflicts so then i tried another way:
if(state.execute("SELECT Str_Column FROM Table WHERE Str_Column = '"+ jTextField.getText() +"'")){
label.setVisibility(true);
}
else{
new frameForSucceedInput.setVisibility(true);
}
the state.execute("SQL") method says:
return true if the query contains results, return false if the query is a update or no contain results
i've tried rs.next() and a lot of things like instead of else do another if(rs==null) but does not work, please help
A quite generic and lighter way is to use the SQL count function .
select count(*) from table where str_Column = ?
You will get that way one record with one value and if the value is higher than 0 then you can show the frame.
Note:
You should use prepared statement so you can set parameters in the query (did you notice the question mark?) instead of concatenating the elements of the query.
You shouldn't mix the code related to the presentation (Swing) with the code related to the DB...but I think you will learn it later.

i need to check whether username is present in db or not.if it is present i shld say already exists..if not i shld insert in db

I need to check whether username is present in db or not. if it is present I should say already exists..if not I should insert in db
code follows:
ResultSet rs=preparedstatement.executeQuery("select *from re where username='"+unt.getText()+"';");
if(rs!=null){
while(rs.next()){
preparedstatement.executeQuery("select *from re where username="+unt.getText()+";");
}
lusn=new JLabel("User Already Exists");
}
else{
preparedstatement.execute("insert into re values('"+nt.getText()+"','"+unt.getText()+"','"+pas.getText()+"','"+add.getText()+"','"+mail.getText()+"','"+ph.getText()+"');");
preparedstatement.executeUpdate();
}
kindly help me out
thanks in advance
Your code is completely unformatted. Format it properly, first of all.
Secondly, you want to check rs.next() to see if a row exists, rather than `rs != null'. You don't want to loop rows at all, just figure out whether one exists already, so there shouldn't be any loop in your code -- just a single IF statement.
Lastly, you want to use ? placeholders & assign parameter values -- not be building up parameters into the SQL string, which is very vulnerable to quoting errors & SQL injection security hacks.

NullPointerException with CallableStatement.getResultSet()

I have a stored proc in SQL Server 2005, which looks like the following (simplified)
CREATE PROCEDURE FOO
#PARAMS
AS
BEGIN
-- STEP 1: POPULATE tmp_table
DECLARE #tmp_table TABLE (...)
INSERT INTO #tmp_table
SELECT * FROM BAR
-- STEP 2: USE #tmp_table FOR FINAL SELECT
SELECT abc, pqr
FROM BAZ JOIN #tmp_table
ON some_criteria
END
When I run this proc from SQL Server Management Studio, things work fine. However, when I call the same proc from a Java program, using something like:
cs = connection.prepareCall("exec proc ?,");
cs.setParam(...);
rs = cs.getResultSet(); // BOOM - Null!
while(rs.next()) {...} // NPE!
I fail to understand why the first result set returned is NULL. Can someone explain this to me?
As a workaround, if I check cs.getMoreResults() and if true, try another getResultSet() - THIS time it returns the proper result set.
Any pointers please? (I'm using JTDS drivers, if it matters)
Thanks,
Raj
The Javadoc for getResultSet() says that it returns null "... if the result is an update count or there are no more results". It looks like your stored procedure would have an update count and a resultset, and that the getResultSet() method is (arguably) just doing what the API contract says it should do.
You could try retrieving the update count first. Otherwise, stick with your "workaround".
Kind of pointless posting an answer after the correct answer has been selected I guess.
The solution I suggest is calling
set nocount on
before the insert statement and
set nocount off
afterwards. Inserts return a resultset otherwise.

Categories

Resources