How to validate username from MySql with JSP - mysql

hello guys i am try to validate username from the database with the username that the user entered in the html from, assume
un//be the variable where username entered now from html form is stored
now how to retrieve all the columns of the uname from user table
uname //column name in mysql for usernames
user //table name in mysql
and check weather the username i.e,un entered now is present or not in the database
i am using
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mebps","root","admin");
Statement stmt = (Statement) con.createStatement();
ResultSet rs = stmt.executeQuery("select un from userinfo");
while(rs.next())
{
if(rs.getString("uname") == un)
{
out.println("user is present");
}
}

There are at least two major mistakes:
You're comparing string instances by == instead of comparing their values by equals() method. The proper line would be if (rs.getString("uname").equals(un)).
You're not letting the DB do the job of returning the right row, instead you're copying the entire DB table into Java's memory and doing the comparison in Java. This is very inefficient. Make use of SQL powers the smart way so that it always returns exactly the information you need. There's for example a WHERE clause.
On an unrelated note, you seem not to be closing DB resources properly after use. This will result in resource leaking which is also a bad idea as it may cause your application to crash on long term. Further, the column name uname and un are not the same. But I'll assume it to be careless oversimplifying of the example.
Here's a minor rewrite:
public boolean exist(String username) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT uname FROM userinfo WHERE uname=?");
statement.setString(1, username);
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return exist;
}
You see, if there's a match, then it returns true (at least one record), otherwise false (no one record). No need to copy the entire table into Java's memory and crawl through it in Java.
Last but not least, this code doesn't belong in a JSP file, but in a normal Java class, starting with a servlet. See also our servlets wiki page to learn more about it.

Related

Checking database's username and data if they match the user info or not

I want to check that the username and data which is already in database is match with the user info or not. I have written some code but it doesn't select a row.
Here is my code:
public boolean iscorrect(String name , String pass){
boolean check=false;
openConnection();
Statement st =null;
ResultSet rs = null;
try{
st = conn.createStatement();
String q = "Select * from signup where email = '"+name+"'" ;
rs=st.executeQuery(q);
System.out.println(rs.getString(1)+" "+rs.getString(2));
if(rs.getString(1).equals(name) && rs.getString(2).equals(pass)){
check = true;
}
}catch(SQLException e){
e.printStackTrace();
}
return check;
}
You need to first call rs.next() to put the cursor at the first row of data. This will return false if there is no data.
In addition to that:
please use PreparedStatement and bind variables to avoid SQL injection
you could put the checks into the WHERE clause instead of loading the whole row
please don't store clear text passwords, use a cryptographic hash function

Safety of not catching SQL Exception

Let's say I have a program that puts email addresses into a database where the email attribute is a primary key.
If I have a duplicate email address, I could deal with it in two ways.
1) run a "select email from table" query. If the email is currently in there, don't add it.
2) don't check if email is in the table. catch(SQLException e), but don't print the stack trace, simply skip over it. This way, if I'm inserting a duplicate it effectively ignores it.
Granted with method 1, I'm only executing a simple select query (no joins or anything fancy) so performance isn't really a huge issue. But if I wanted to optimize performance, would method 2 be a viable, safe way of doing this?
So instead of running a "select ..." every time, I just add it.
Are there any safety issues with skipping over the exception?
Java Example (with JDBC):
try {
String sql = "insert into emails values(?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, email);
pstmt.execute();
return true;
}
catch(SQLException e) {
// e.printStackTrace(); // skip; don't print out error
return false;
}

Why there are many connections in this case (MySQLNonTransientConnectionException)

I am getting an exception using PreparedStatement to select.
Got an exception accessing TestCase data! null
Problem to connect.
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Too many connections
Here is my code:
public Integer getTypeByInputAndProblemId(String inputTestCase, Long problemId) {
String sql = "SELECT type FROM test_case where problem_id= ? and input= ?";
Integer type = 0;
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1, problemId);
ps.setString(2, inputTestCase);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
type = new Integer(rs.getInt("type"));
}
rs.close();
ps.close();
} catch (Exception e) {
System.err.println("Got an exception accessing TestCase data! " + e.getMessage());
}
return type;
}
In line PreparedStatement ps = connection.prepareStatement(sql);
my problem is because connection sometimes is Null (the debug shows this).
I'm guessing this is because of many connections, but I don't know why this is happening.
I would like some help, please!
Yes, the issue happens because your server is reaching the max number of multiple connections accepted by your MySQL Server.
First, you need to see if you have a proper number configured in MySQL for multiple connections: max_connections. If this look low to you, you can increase this number in order to "fix" this issue.
Secondly, if the number makes sense, you're probably using more connections than you think you are. Probably because you're opening connections in your application and not closing them.
Check how many multiple connections your server have used so far.
show status like 'Max_used_connections';
This number is reset when you restart your database service.

Obscure MySql Connector/J error message - java.sql.SQLException: boo {exclamation mark}

What the hey does this MySql error message mean?
java.sql.SQLException: boo!
springframework.dao.TransientDataAccessResourceException: CallableStatementCallback; SQL [{call sp_MyStoredProc(?, ?, ?)}]; boo!
It's not particularly meaningful that's for sure. Has anybody come across this and is able to translate to less lazy~developer~ish...?
I am accessing via org.springframework.jdbc.object.StoredProcedure
I am using org.springframework.jdbc-3.1.3
#Update
The offending lines are in CallableStatetement.java (2269-2271)
if (!found) {
throw SQLError.createSQLException("boo!", "S1000", this.connection.getExceptionInterceptor());`
}
Attching the sources for mysql-connector-java-5.1.18.jar and tracing though the code reveal that the correct message should be along the lines of 'mismatch between declared and actual parameters' or similar.
Indeed correctly declaring my output parameter
declareParameter(new SqlOutParameter("output", Types.INTEGER));
rather than
declareParameter(new SqlParameter("output", Types.INTEGER));
fixed my problem. But a more meaningful error message would have saved precious time. I shall make this suggestion to the MySql Connector/J Development team.
As stated in the update to the question this is commonly caused by incorrectly using a CallableStatement. For example:
Stored Procedure uses 2 parameters, one in and one out:
CREATE DEFINER=`example`#`localhost` PROCEDURE `sp_getSensorLocation`(IN in_id VARCHAR(128), OUT loc VARCHAR(128))
BEGIN
SELECT LOCATION INTO loc FROM table.SENSORS
WHERE ID = in_id;
END
but the call to it only uses 1:
private String getSensorLocation(String sensorID) {
String location = "";
Connection c = dbr.getConnection();
String prepStatement = "{ call sp_getSensorLocation(?) } ";
try {
callableStatement cs = c.prepareCall(prepStatement);
cs.setString(1, sensorID);
ResultSet rs = cs.executeQuery();
if (rs.next()) {
location = rs.getString(1);
}
} catch (SQLException ex) {
LOG.error("Error:", ex);
}
dbr.closeConnection(c, rs, cs);
return location;
}
When the correct code is really:
private String getSensorLocation(String sensorID) {
String location = "";
Connection c = dbr.getConnection();
String prepStatement = "{ call sp_getSensorLocation(?, ?) } ";
try {
CallableStatement cs = c.prepareCall(prepStatement);
cs.setString(1, sensorID);
cs.execute();
location = cs.getString(2);
} catch (SQLException ex) {
LOG.error("Error:", ex);
}
dbr.closeConnection(c, rs, cs);
return location;
}
Notice I also changed to cs.execute as I don't expect a result set and would have issues with this as well (the example is taken from someone else's code I'm fixing, the joys -_-)

Update table on mysql after a bigdecimal is declared

I have the following work on my application, in which I am trying to update the value total on my mysql database table called "porcobrar2012". However, the only value that gets updated is the last one generated in the while loop. Why? all values are been printout on the screen with no problem, but those values are not getting updated in the database.
Here is the code:
BigDecimal total = new BigDecimal("0");
try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Connection connection=DriverManager.getConnection("jdbc:odbc:db1","","");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost/etoolsco_VecinetSM?user=etoolsco&password=g7Xm2heD41");
Statement statement=connection.createStatement();
String query;
query="SELECT * FROM porcobrar2012";
ResultSet resultSet=statement.executeQuery(query);
while(resultSet.next())
{
out.println(resultSet.getString(2)+"");out.println(resultSet.getBigDecimal(3)+"");out.println(resultSet.getBigDecimal(4)+"");out.println(resultSet.getBigDecimal(5)+"");out.println(resultSet.getBigDecimal(6)+"");out.println(resultSet.getBigDecimal(7)+"");out.println(resultSet.getBigDecimal(8)+"");out.println(resultSet.getBigDecimal(9)+"");out.println(resultSet.getBigDecimal(10)+"");out.println(resultSet.getBigDecimal(11)+"");out.println(resultSet.getBigDecimal(12)+"");out.println(resultSet.getBigDecimal(13)+"")out.println(resultSet.getBigDecimal(14)+"");out.println(resultSet.getBigDecimal(15)+"");
total = resultSet.getBigDecimal(3).add(resultSet.getBigDecimal(4)).add(resultSet.getBigDecimal(5)).add(resultSet.getBigDecimal(6)).add(resultSet.getBigDecimal(7)).add(resultSet.getBigDecimal(8)).add(resultSet.getBigDecimal(9)).add(resultSet.getBigDecimal(10)).add(resultSet.getBigDecimal(11)).add(resultSet.getBigDecimal(12)).add(resultSet.getBigDecimal(13)).add(resultSet.getBigDecimal(14)).add(resultSet.getBigDecimal(15));
String query1;
query1="UPDATE porcobrar2012 SET total=total";
PreparedStatement ps = connection.prepareStatement(query1);
ps.executeUpdate();
out.println(total);
}
connection.close();
statement.close();
}
catch (Exception e)
{
//e.printStackTrace();
out.println(e.toString());
}
It's because the update closes the existing result set. But I would ask why you aren't doing the addition in a single UPDATE statement without any prior query, at the database, no loops, no BigDecimals. Rule one of database programming is 'don't move the data further than you need to'. It would be many times as efficient to just write "UPDATE porcobrar2012 SET a=b+c+d+...". And you can remove the Class.forName() call too: it hasn't been required for years.