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

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.

Related

UCASE and UPPER sql functions

I am trying to do the following query:
String query = "SELECT * FROM EMP WHERE UCASE(LAST_NAME) ";
query += "LIKE '" + lastName.toUpperCase() + "%'";
in an example of usage of an servlet to access to a database
But I am getting the error message:
Excepcion java.sql.SQLSyntaxErrorException: ORA-00904: "UCASE": invalid identifier
On the other hand, when I use the UPPER sql function, the example works but the results do not show the values of the LASTNAME column in uppercase. I do not understand what happens.
You're just comparing the upper case values, but you're selecting the actual values with select *
to get the uppercase name in your resultset you need to use UPPER in your select list, not UCASE, like this:
String query = "SELECT UPPER(LAST_NAME) AS UPPERNAME, * FROM EMP WHERE UPPER(LAST_NAME) ";
query += "LIKE '" + lastName.toUpperCase() + "%'";
What your code is doing here is building a query string named query. Once query is complete, it will be sent to the database for parsing and running.
When you are building a query to the database, you have to use the built-in database functions for the part of the query that the database is going to parse and run. So, in your example, Java is doing toUpperCase on lastName and then putting that literal into the query string that will go to the database. UPPER(LAST_NAME) is going into the query string as is, it will get passed to the database just like that and run by the database. So it needs to be a function that the database can parse and run: an Oracle function, not a Java function.
UCASE is a DB2 function & not Oracle. For Oracle, you need to use UPPER .
Second part of your question is already answered by James Z.
Having said that, I am answering because previous answers didn't pointed out SQL injection problem with the way you listed your query.
Make it a habit to always execute parametrized queries with jdbc & not by directly appending values to query string.
String query = "SELECT * FROM EMP WHERE UCASE(LAST_NAME) LIKE ? ";
Your parameter would be - lastName.toUpperCase()+"%"
SQL Injection

Special characters in SQLiteDatabase android

I am at the verge of finishing my first android app. But I am stuck wondering something about saving special characters in SQLite Database.
When I take data from a edit view and put that data into my database, I am able to input all the special characters without handling anything.
for eg.
EditText editText1 = (EditText) findViewById(R.id.user_name);
String name = editText1.getText().toString();
db.execSQL("INSERT INTO DETAILS VALUES('" + name + "');");
Now the PROBLEM
even if I input ), (, ", * or any other special character, its able to insert that data
BUT as soon as I enter ' (apostrophe), there is an error(Log shows syntax). I have read almost every question related to special characters on stackoverflow but still I am not able to understand that even using ( or ) or " should generate a syntax error, same as in the case of apostrophe. Then why does it happen. Even though it works for me, but I am curios. Also what is the best way to escape these special characters ?
Thanks in advance
Do not use execSQL() for this!
SQLiteDatabase.insert() will build the statement for you, and also avoid any problem with special characters in the parameters.
ContentValues values = new ContentValues();
values.put("FIELD_NAME", name);
db.insert("DETAILS", null, values);
To understand what is happening, just check what is the resulting SQL statement from adding the parameter:
name = Scarlett -> INSERT INTO DETAILS VALUES('Scarlett'); (Ok)
name = O'Hara -> INSERT INTO DETAILS VALUES('O'Hara'); (Wrong)
Since the apostrophe is the string delimiter in SQL, there is one 'O' string plus Hara' which is not a valid token. In this case it just produces an error, but a maliciously crafted string could produce valid SQL which does unintended things.
That's why concatenating strings is a VERY BAD PRACTICE (TM) when writing SQL statements, as it can lead to SQL Injection. Remember the story of Bobby Tables!
To enter an apostrophe, you have to double it ('').
Because an apostrophe is a special character which delimits SQL strings.
So:
String sql = "INSERT INTO DETAILS VALUES('" + name + "')";
db.execSQL(sql.replaceAll("'", "''"));
Even better, you could bind your parameter:
db.execSQL("INSERT INTO DETAILS VALUES (?)", new String[]{name});
The ? is replaced and converted by the parameter passed as new String[]{name}
So, you don't even have to care about the ' characters in your string.
To answer the question in your comments:
A valid SQL String might be:
'This is an apostrophe: ''; this is a quote: "; this is an asterisk: *, ...'

no such column in sqlite android java

i try to retrieve data from sqlite with this code:
String sql = "select * from "+Table +" where "+C_LoginName+"=" +user;
Log.d("CREATE DATABASE", "SQL: " + sql);
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
Log.d("Password is", c.getString(c.getColumnIndex(C_Password)));
but this error shown to me ("no such column....")
i even use single quot(') side every string but not different.but when i use select * from table the loginName is there.
how can solve that?
tnx
Quotes missing around user. Also, make sure C_LoginName contains a valid column name.
String sql = "select * from "+Table +" where "+C_LoginName+"='" +user + "'";
no such column in sqlite android java
This kind of error is usually thrown:
When you forgot to wrap column's value into single quotes (if you are
not using parametrized statements)
You specified icorrect column name(check your database schema)
Recommendation:
I don't like your approach. It's dirty, not very human-readable and very unsafe. I suggest you to use parametrized statements with placeholders where each placeholder will be replacted with value from specified array.
Example:
String query = "select * from tablename where name = ?";
db.rawQuery(query, new String[] {name}); // ? will be replaced with name value
Note:
Usually if you are dealing with database it's very good and handy practise to create some class for example called Const that will hold your column names as final static variables.
This provides more efficient and cleaner dealing with database and you'll avoid typo problems (which are too hard to find out).

jdbc code to update informations in a mysql table

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 :)

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

Categories

Resources