Comparing user input to mysql database value - java

public void datuieguve(){
Scanner ievads = new Scanner(System.in);
String lietotIn = ievads.next();
// String paroleIn = ievads.next();
try {
quer = savien.createStatement();
String kverijs = "select lietotajvards from lietotaji where lietotajvards = '" +lietotIn+ "';";
rezult = quer.executeQuery(kverijs);
System.out.println(rezult.next());
String lietotajvards = rezult.getString("lietotajvards");
if (rezult.equals(lietotIn))
{
System.out.println("Yup");
}
else
{
System.out.println("Nope");
}
} catch(Exception ex) {
System.out.println("Kluuda: " +ex);
}
ievads.close();
}
Hi guys, I'm trying to create a code that will take user input and compare it with mysql database value. The problem is, it's not working and I'm stuck. I'd appreciate if someone could figure out what's wrong with my code and give me some tips or something, because I can't :)
I think I got down the connection part but the comparison is driving me nuts.

Make these changes on your code :
while(rezult.next()){
String lietotajvards = rezult.getString("lietotajvards");
if(lietotajvards.equals(lietotIn))
{
System.out.println("Yup");
}
...
}
Edit:
Its good practice to use prepared statement instead of create statement.
Ex:
Connection db = con.getConnection();
try {
PreparedStatement ps = ...;
try {
ResultSet rs = ...
try {
...
}
finally {
rs.close();
}
}
finally {
ps.close();
}
}
finally {
db.close();
}

Related

Printing a query from a database

I am trying to access a database and print off a query.
I am trying to access a DEVICE table and print off the DEVICE_ID, but i am unsuccessful so far.
Here is my code at the moment;
public static void main(String[] args) throws FileNotFoundException {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
Preferences sysRoot = Preferences.systemRoot();
Preferences prefs = sysRoot.node("com/davranetworks/zebu");
url = prefs.get("dburl", "jdbc:hsqldb:E:\\eem\\eemdb");
} catch (Exception e) {
e.printStackTrace();
}
Connection c = getConnection();
try {
c.setAutoCommit(true);
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = s.executeQuery("SELECT * FROM eem_db.device");
ResultSet deviceId = s.executeQuery("select device_id from eem_db.device");
System.out.println(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection c = null;
try {
c = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("Error initialising connection" + e);
}
return c;
}
The returned value is org.hsqldb.jdbc.JDBCResultSet#1d3d68df.
I don't know what this value relates to as I was expecting 3 integer values.
Can anyone help me on this?
You have to iterate over the rows contained in the ResultSet and for each row get the column you want:
ResultSet deviceIdRS = s.executeQuery("select device_id from eem_db.device");
while(deviceIdRS.next()) {
System.out.println(deviceIdRS.getString("device_id"));
}
You must use the ResultSet getXXX method that correspond with your column type, for example, getInt, getString, getDate...
That ResultSet deviceId is actually an object contains rows of result from your sql, so you only can see the memory address when you print it out.
You need something like:
while(deviceId.next()){
System.out.print(deviceId.getInt(1));
}
s.executeQuery("select device_id from eem_db.device"); is returning a resultSet, you must find out the value from result set.
like
int device_id = resultset["deviceId"];
while (deviceId.next())
{
// Printing results to the console
System.out.println("device_id- "+ deviceId.getInt("device_id");
}
iterate object using resultset.
You are printing object of ResultSet, it won't give you the right values.
You need to iterate the loop like below
while(deviceId.next()) {
int integerValue = deviceId.getInt(1);
System.out.println("content" + integerValue)
}
deviceId.close();
s.close();

JDBC ResultSet is giving only one row although there are many rows in table?

I am having many rows in table and I ran the same query on my database which is MySql but java ResultSet is only giving the first row of the table. Here is my code.
public ArrayList<String> getAllAlbumsName(Integer uid) {
ArrayList<String>allAlbumsName = new ArrayList<String>();
try {
String qstring = "SELECT albumname FROM picvik_picture_album WHERE " +
"uid = '" + uid + "';";
System.out.println(qstring);
connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
ptmt = connection.prepareStatement(qstring);
resultSet = ptmt.executeQuery();
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
resultSet.close();
ptmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return allAlbumsName;
}
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
If you would like to get all rows, it should be:
while(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
The while statement continually executes a block of statements while a particular condition is true
Note: As #BalusC commented, your code would introduce SQL Injection attack, it is better to use ptmt.set... Instead of constructing SQL String manually.
try while(resultSet.next()) {
instead of if (resultSet.next()) {
Change if (resultSet.next()) { to while (resultSet.next()) {

When injecting into a sql query using java, gets an error

public ArrayList<Message> searchMessages(String word) throws DaoException{
ArrayList<Message> messages = new ArrayList<>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
//String query = "SELECT * FROM messages WHERE text LIKE %?% order by date";
String query = "SELECT * FROM messages WHERE text LIKE '%?%'";
ps = con.prepareStatement(query);
ps.setString(1,word);
rs = ps.executeQuery();
while (rs.next()) {
int messageId = rs.getInt("messageId");
String text = rs.getString("text");
String date = rs.getString("date");
int memberId2 = rs.getInt("memberId");
Message m = new Message(messageId,text,date,memberId2);
messages.add(m);
//Company c = new Company(companyId, symbol, companyName, sharePrice, high, low);
//companies.add(c);
}
} catch (SQLException e) {
throw new DaoException("searchMessages(): " + e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
freeConnection(con);
}
} catch (SQLException e) {
throw new DaoException("searchMessages(): " + e.getMessage());
}
}
return messages;
}
Just explain the code a little first.It simply just searches the messages table and its field of text for whatever is supplied.I use a prepared statement to insert it into the query and run it.No matter what string i supply it gives this error
oow_package.DaoException: searchMessages(): Parameter index out of range (1 > number of parameters, which is 0).
No idea why it isn't working in the slightest. Would appreciate any help.
You can't use such a parameter in a prepared statement. The query should be
SELECT * FROM messages WHERE text LIKE ?
And you should use
ps.setString(1, "%" + word + "%");
I'm no expert, but i'd say your prepared statement is recognized with no parameters, and you still insert one (word)... maybe the trouble comes from the % sign?
EDIT: agree with the guy above... seems legit.

Using PreparedStatement template issue

Here's my static utility:
//String sqlQuery = "select count(name) as num from tbname where name = ?"
//String name = "testString";
private static int correct(Connection connection, String sqlQuery, String name) {
int result = 0;
PreparedStatement statatement = null;
ResultSet rs = null;
try {
statatement = connection.prepareStatement(sqlQuery);
statatement.setString(1, name);
rs = statatement.executeQuery();
while (rs.next()) {
result = rs.getInt("num");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
statatement.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
}
The method above returns 0 (incorrect result), but the following one returns '1' (it works OK, it the same sql query):
//String sqlQuery = "select count(name) as num from tbname where name = 'testString'"
private static int correct(Connection connection, String sqlQuery, String name) {
int result = 0;
PreparedStatement statatement = null;
ResultSet rs = null;
try {
statatement = connection.prepareStatement(sqlQuery);
rs = statatement.executeQuery();
while (rs.next()) {
result = rs.getInt("num");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
statatement.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
}
Could you please give me any advise, so I could resolve the problem.
PS: I'm not sure if it does matter, but the actual streetName - has a name in windows-1251 encoding (Russian) text.
PPS: The database is Oracle 10.
It might be a character set issue. According to the Oracle JDBC Drivers release 10.1.0.2.0 (10g) README:
The following is a list of known
problems/limitations:
If the database character set is AL32UTF8, you may see errors under the
following circumstances:
accessing LONG and VARCHAR2 datatypes.
binding data with setString() and setCharacterStream().
So if your database character set is AL32UTF8, you might have to get it changed to something else.
Also, what is the datatype of your column? VARCHAR2?
It seems the encoding conflict with the one which you set in your DB encoding charset and the the String you are passing..
You can do these 2 tries
Set the DB encoding to UTF-8 and then give a try. If this does not work you may go with following 2nd option
Set DB encoding charset to UTF-8 and also set the String by using this String constructor String(byte[] bytes, String charsetName)

Java skips else condition

I'm not sure why, but for some reason, the following code skips the else condition. I've tried just about everything I can think of, including switching the code blocks, but it still skips the else part. Basically, I want this method to return String temp = "no" if String docID that is passed to the method is not found in the FILESTATUS database, and String temp = "yes" if it is found.
static String checkDocID(String docID)
{
String temp = null;
System.out.println("Checking if data already exists in database...");
try
{
Main.stmt = Main.con.createStatement();
String command = "SELECT * FROM FILESTATUS WHERE ID='" + docID + "'";
ResultSet queryResult = Main.stmt.executeQuery(command);
if (!queryResult.next())
{
temp = "no";
}
else
{
while (queryResult.next())
{
String result = queryResult.getString("ID");
if (result.equals(docID))
{
temp = "yes";
break;
}
}
}
Main.stmt.close();
}
catch (Exception ex) {ex.printStackTrace();}
return temp;
}
Thanks!
Because you end up calling queryResult.next() in the "if" and again in the while, you're skipping the first result. If there is only one result, the while loop will never execute.
If I can make a couple of suggestions:
Use bound variables in a PreparedStatement rather than putting "docID" in the query string
Don't test result.equals(docID) since the query already assured that.
prefer boolean to String "yes" or "no"
set the result to "no" or false, then set it to "yes" or true in the loop. The extra assignment is probably faster than the extra test, plus you can skip the do{}while which most people find harder to read.
Might be better to restructure this loop as:
static String checkDocId(String docId) {
String temp = "no";
while (queryResult.next()) {
String result = queryResult.getString("ID");
if (result.equals(docID)) {
temp = "yes";
break;
}
}
return temp;
}
Some people don't like using break (I usually don't) so you can use a boolean in your while (I find that it reads more like english and you can tell the terminating condition right from the while instead of looking for an if inside):
static String checkDocId(String docId) {
boolean found = false;
while (queryResult.next() && !found) {
String result = queryResult.getString("ID");
found = result.equals(docID);
}
return found ? "yes" : "no";
}
You're performing a needless comparison otherwise. Remember, a while is just an if with a goto at the end ;)
As far as your problem is concerned, what Paul said is correct. Eitherway, I would still restructure the loop so that it's more elegant.
After a bit astonishment about the code (leaking DB resources, not trusting the DB that it returns the right docID, doing a SELECT * while you don't need all of the columns at all, not taking benefit of SQL-injection-sanitization powers of PreparedStatement, using String instead of boolean to denote a true/false value, a messy code flow), here's how it should really be done instead:
private static final String SQL_EXIST_DOCID =
"SELECT id FROM filestatus WHERE id = ?";
public boolean exist(String docID) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_EXIST_DOCID);
statement.setString(1, docID); // Shouldn't it be a Long instead? Characterbased PK's are *far* from efficient.
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return exist;
}
Clear, concise and simple as that. For more insights about using basic JDBC the right way you may find this article useful. I hope that you take it serious to learn from it. Really.
You are calling queryResult.next twice before you are trying to read it. To prove this, put a println or something right after the else (before the while).
Since you are selecting by a particular ID, moving to next() twice will in fact fail the second time (presumably) and never execute the while block.
rs.next() rolling current cursor after each call
try with
static String checkDocID(String docID)
{
String temp = null;
System.out.println("Checking if data already exists in database...");
try
{
Main.stmt = Main.con.createStatement();
String command = "SELECT * FROM FILESTATUS WHERE ID='" + docID + "'";
ResultSet queryResult = Main.stmt.executeQuery(command);
boolean found = queryResult.next();
if (!found)
{
temp = "no";
}
else
{
do {
String result = queryResult.getString("ID");
if (result.equals(docID))
{
temp = "yes";
break;
}
} while (queryResult.next())
}
Main.stmt.close();
}
catch (Exception ex) {ex.printStackTrace();}
return temp;
}

Categories