Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'd like to make this into a boolean that will return true or false.
I simply got no idea how to , so I need some help.
public static void checkUSPASS(String a,String b) {
try {
con = DriverManager.getConnection(url,username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql;
sql = "SELECT * FROM db Where Email='"+a+"' and Password='"+b+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
//return true
}
else
{
//return false
}
}
catch (SQLException ex) {
ex.printStackTrace(); }
}
I should probably get all declarations out , but I'd like to hear what do you think guys.
While this is not the answer to your question, but I believe it will help you to make your method better. Probably comment will be more suitable, but comments with large piece of text are hard to read.
Don't use SQL query string composition like you do. Use PreparedStatement instead of that.
Process exceptions inside of your method or throw them further. Printing stack trace is not the exception processing, it hides the problem from the end-user.
To throw the exception further add throws SQLException to your method declaration, and remove try/catch construction from the method body. It will allow the caller to process the exception and will avoid many hard-to-catch bugs later.
Don't store passwords as Strings, it is a bad practice. Hash passwords with salt and store password hashcode.
And finally your method declaration should look like that:
public static boolean checkUSPASS(String username,String hashCode) throws SQLException
First change the method signature to return a value:
public static boolean checkUSPASS(String a,String b)
Then return a value from within the method:
return true;
or:
return false;
Note that all code paths must return some value. So you have this in your try block:
if (rs.next()) {
return true;
}
else {
return false;
}
But in the event of reaching your catch block, something must still be returned:
catch (SQLException ex) {
ex.printStackTrace();
return false;
}
To change a function to boolean in java all you have to do is change void to boolean in your function definition and return true or false at all end points.
Related
End of try block, or after all blocks?
I read a lot of answers on stack overflow about what will happen in each case. However, I could not find out which one is the commonly accepted "corrected" place to return.
Object o = null;
try {
Connection c = getConnection();
o = c.getThing();
return o;
} catch (Exception e) {
//handle exception
return null;
} finally {
c.close();
}
vs
Object o = null;
try {
Connection c = getConnection();
o = c.getThing();
} catch (Exception e) {
//handle exception
return null;
} finally {
c.close();
}
return o;
It completely depends on what you are trying to do. See the following code for some examples of the possibilities (not all of which should be combined in any single piece of code!).
try {
// do something that may fail
return 0; // return a normal value
} catch(SomeException e) {
// maybe log an error
return -1 // maybe return a default or error value
} finally {
// maybe clean up resources
// finally will be executed even if you return in try or catch
// a return here will trump a return in try/catch. This is generally regarded as a bad idea
// see https://stackoverflow.com/questions/65035/does-finally-always-execute-in-java
}
return 1 // return a normal value here instead of in the try/catch.
// May be clearer than multiple return statements
// Also useful if return value does not depend on the try/catch outcome
Update for your updated question. It's partly a matter of preference, though there are significant reasons for each choice. Many people prefer a single point of return, so would do this:
Object o = null;
try {
Connection c = getConnection();
o = c.getThing();
} catch (Exception e) {
//handle exception; leave o as null
} finally {
c.close();
}
return o;
Although this sounds like it should be clearer, of course one still has to examine the code to determine what value(s) o may end up with, so the advantage isn't great.
However, the other options have the advantage that the returning of null is very explicit. This is good if you are one of the many programmers who consider returning null values to be generally a bad idea (see Tony Hoare's "billion dollar mistake").
Instead of returning null one can use "Optional", "Option" or "Maybe" types (available in e.g. Java 8, Scala, Haskell and the Functional Java library), or use the Null Object pattern.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a small program for inserting data into a database with http.
I made a function to do this but when i call the function in my main file it seems that it does not work. I tried debugging it but when I set a breakpoint on the line it does not show that the function is used. Can someone help me?
public class School_Planner {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HTTP_Conncetion.Connect();
}
}
.
public class HTTP_Conncetion {
public static void Connect(){
try {
// open a connection to the site
URL url = new URL("http://localhost:8080/HTTP_Connection/index.php");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
// send your parameters to your site
ps.print("firstKey=firstValue");
//ps.print("&secondKey=secondValue");
// we have to get the input stream in order to actually send the request
con.getInputStream();
// close the print stream
ps.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
EDIT
After the command of Jon Skeet, i think i have to be a little more specific. The problem i think is that the function does not work or that it skips over the function.
The posted code is just fine it calls the URL
http://localhost:8080/HTTP_Connection/index.php
with the parameter firstKey and its value firstValue
Unless you forgot to do the imports which would result in a compile error to begin with.
I guess your error is on the server side. Please double check the server.
For sure your question is very unspecific - no exception, no exact description of what "function" you think is not called. Not what you expect to happen and what you miss of happening. Please adjust your question in a way that there can be a more concrete answer to your question.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am having a problem of how to call a method once when the condition achieves many times! for example:
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened){
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
Please help with that
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened){
if (!isAlreadyCalled){
callAMethodOnce();// this method is called once even if the condition achieved again
isAlreadyCalled = true;
}
}
}
boolean isHappendBefore = false;
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened && (! isHappendBefore) ){
isHappendBefore = true;
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
You could simply set a flag. If you just need it to only happen once with each instance of the Activity then set a member variable.
public class MyActivity extends Activity
{
boolean itHappened = false;
...
public void onLocaitonChanged(Location location)
{
// this if statement may achieve the condition many times
if(somethingHappened && !itHappened)
{
callAMethodOnce();// this method is called once even if the condition achieved again
itHappened = true;
}
}
If you want it to only happen once ever in the life of the application then set that variable as a SharedPreference
set a class wide boolean
if(!hasRun){
callAMethodOnce();
hasRun = true;
}
Maybe I don't understand your question correctly but from your problem definition I would suggest using a boolean variable something like.
boolean run = false;
public void onLocaitonChanged(Location location){
// this if statement may achieve the condition many times
if(somethingHappened && run == false){
run = true;
callAMethodOnce();// this method is called once even if the condition achieved again
}
}
Once the code under if statement gets executed once run would be true and there won't be any subsequent calls to callAMethodOnce()
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have defined a function:
public MyCar findCar(){
MyCar car = CarManager.findCarById("U983"); //Nullpointer Exception here if no car be found
if(car!=null)
return car;
else
return null;
}
When I invoke the above function in Java, If the above CarManager.findCarById() did not find any car, it returns null, and I try to check in if condition that if it is null return null other wise return the car.
But the findCar() function always stop and raise Nullpointer Exception when findCarById() did not find any car, without go through my if condition. How to get rid of it?
============ findCarById() is a library API I can not modify =================
Throwing or catching NullPointerException is not a really good idea. If you can modify that findCarById, change it.
Otherwise, you can do try-catch here.
MyCar car = null;
try {
car = CarManager.findCarById("U983");
} catch (NullPointerException e) {
car = null;
}
Check (or post) method "findCarById" in your static CarManager class.
You're saying that the findCar() method you posted is throwing a NullPointerException? That's not possible since there are no object dereferences in that method.
Also, that whole if condition is pointless. It's saying "if car is null, return null, else return the car". You might just as well say return car; - it will have exactly the same effect.
How about modifying findCar() like this :
public MyCar findCar(){
MyCar car = null;
try {
car = CarManager.findCarById("U983"); //Nullpointer Exception here if no car be found
}
catch (Exception e){
e.printStackTrace();
}
return car;
}
First of all, I'm new to Java.
I'm trying to figure out what would be a good/handy way to work with DB from Java. I'm using c3p0 for connection pooling. Hibernate or other ORM is not an option this time, we decided to stick with "plain SQL" for now.
Currently basic retrieval of data looks like this:
private int getUserID(int sessionID, String userIP) {
int result = 0;
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
// Application.cpds is an instance of c3p0's ComboPooledDataSource
conn = Application.cpds.getConnection();
st = conn.prepareStatement("SELECT user_id, user_ip, is_timed_out FROM g_user.user_session WHERE id = ?");
st.setInt(1, sessionID);
rs = st.executeQuery();
if ( rs.next() ) {
if ( !rs.getBoolean("is_timed_out") && userIP.equals(rs.getString("user_ip")) ) {
result = rs.getInt("user_id");
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
if ( rs != null ) {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if ( st != null ) {
try { st.close(); } catch (SQLException e) { e.printStackTrace(); }
}
if ( conn != null ) {
try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
return result;
}
The code looks very long for such a basic operation. Another problem is that most of the code would have to be repeated in many places (declaring Connection, PreparedStatement, ResultSet, closing them, catching exceptions). Though, this is what I see in most examples when googling.
In PHP I would create a wrapper class that would have method select() that accepts 2 arguments (string)sqlQuery and (array)parameters and would return simple array of data. Wrapper class would also have few more specific methods, like:
selectValue() for single value (e.g., select count(*) from user)
selectRow() for single row (e.g., select name, surname from user where id = :user_id)
selectColumn for single column (e.g., select distinct remote_address from user)
Is anything like this practiced in Java? Or is there anything better / handier? Or should I use same style as in getUserID() example above? As I said, ORM is not an option this time.
Thanks in advance :)
edit: Currently DBConnection class is written. It gets connection from c3p0 connection pool in constructor. It has few public methods for working with DB: select() for tabular data, selectValue() for single value, selectRow() and selectColumn() for single row or column, as well as insert(), update(), delete() and ddl(). Methods accept String query, Object[] params arguments, with params being optional. insert(), update() and delete() return Integer which is result of PreparedStatement.executeUpdate(). select methods return different results:
ArrayCollection<HashMap<String, Object>> select()
Object selectValue()
HashMap<String, Object> selectRow()
ArrayCollection<Object> selectColumn()
The last problem is with compiler warnings - "warning: [unchecked] unchecked cast". This is because all methods call single private method that returns Object and cast its result to mentioned types. As I am new to Java, I'm also not sure if I have chosen appropriate types for selects. Other than that, everything seems to work as expected.
If the an ORM is no option, you could still use Spring's JDBC helper classes:
http://docs.spring.io/spring-framework/docs/4.1.0.RELEASE/spring-framework-reference/html/jdbc.html
Or you could simply write some helper methods on your own. Maybe a DBUtil.close(conn, st, rs); would be nice.
And by the way, you really should use a logging framework instead of "e.printStackTrace()"
EDIT:
One more thing: I think it's kind of hard to add ORM afterwards, when you have all the SQL already written in plain JDBC. You can't refactor that stuff, you have to throw it away and do it again.
EDIT:
You don't have to close the resultSet if you are closing the statement anyway. The Java ResultSet API reads:
A ResultSet object is automatically
closed when the Statement object that
generated it is closed, re-executed,
or used to retrieve the next result
from a sequence of multiple results.
Beside that, C3P0 does resource management as well and and closes Statements when you return a connection. You might to look that up too.
To avoid the repetition of code and perhaps makes things simpler.
What you could do is create a Database class.
In the class you could then create general purpose methods for access to the database.
For eg.
if the class is called DBManager.java then inside
create methods
private connect()
public boolean update()
public ResultSet query()
Reason for connect method is obvious, you use it get your connection. Since its private you call it in the constructor of DBManager.
You then use your update() method to allow you to perform SQL inserts,update,delete and the like, basically any SQL operation that doesn't return any data except for maybe a status of its success is done with the update method.
Your query method is used when you want to do a select query. You can thn return the resultset and then iterate through the results in the calling method/class
How you handle exceptions is up to you. It may be nicer on you to handle exceptions in the DBManager class that way you won't have to handle them in the various classes that you make a query from.
So instead of
public ResultSet query() Throws SQLException{
you would use a try catch inside the query method like you did in your examples above.
The obvious advantage of handling it in the dbmanager class is that you won't have to worry about it in all the other classes that make use of your sql connection.
Hope that's helpful
in response to your comment:
Its up to you what you return, the ResultSet being return is only an idea but maybe it'd be best to return a collection of some sort instead of an array, maybe? depending on what you need. The resultset needn't be closed.
public ResultSet query(String strSql) {
try {
Statement tmpStatement = connection.createStatement();
ResultSet resultSet = tmpStatement.executeQuery(strSql);
return resultSet;
} catch (java.sql.SQLException ex) {
//handle exception here
return null;
}
}
your update can then look like so
public boolean updateSql(String strSQL) {
try {
Statement tmpStatement = connection.createStatement();
tmpStatement.executeUpdate(strSQL);
return true;
} catch (java.sql.SQLException ex) {
//handle exception
return false;
}
}
erm, you can then use your query method like so
ResultSet r = query(sql);
try {
while (r.next()) {
someVar[i] = r.getString("columnName");
}
} catch (SomeException ex) {
//handle exception etc
}
But then again as you said instead of returning a result set you could change the query method to copy your results to an array or collection and then return the collection and close the statement with
tmpStatement.close();
But when a Statement object is closed, its current ResultSet object, if one exists, is also closed.(from api docs)
Its good practice to free up database resources as soon as so copying your result to a collection object and then closing your statement is probably best. Again its up to you.
" Hibernate or other ORM is not an option this time, we decided to stick with "plain SQL" for now."
Out of curiosity, what was the reason to stick with plain SQL? Looking at the example and question you mentioned first obvious answer would be use ORM and don't bother - in most cases standard ORM feature list would be sufficient.
Obviously there are plenty of reasons not to use ORM's, so I'm interested in yours?
I think the level o granularity is always a developer decision. I mean, the great thing of having so many exceptions and validations is that you can capture the specific error and act according to it, however if what you need doesn't require that level of robustness and as you are showing it is just to print out the stack trace, I think a wrapper method can be useful in your case.