SQL check if table contains value? - java

I´m new to SQL. My goal is, to create a program, which should check whether a certain table has a certain value. I´ve wrote this method
public boolean existString(final String query) {
try {
final Statement statement = this.conn.createStatement();
result = statement.executeQuery(query);
return true;
} catch(SQLException e) {
e.printStackTrace();
return false;
}
}
As you can see, its a method for executing a SQL-statement. I think this may be the right statement :
String query = "select * from table where column1 = 'checkvalue'"; // of course i need to replace table and column and checkvalue
But atfer executing this statement, how can I prove if it was successfull (Does the query return something)? If the statement, after executing would return something, I could easly use a if-statement to check.

A SQL statement can return successfully if there are no rows returned from the database, so using a SQLException is not going to help you if the query is correct but there is no match.
public boolean existString(final String query) {
try {
final Statement statement = this.conn.createStatement();
result = statement.executeQuery(query);
return result.next();
} catch(SQLException e) {
e.printStackTrace();
return false;
}
}
You should leverage the fact that result.next() attempts to move the result pointer to the next row and return whether or not there is a row to return. This way, if successful and there is results ir returns true and of successful and not results, it returnsfalse. If something goes wrong, you're exception handling will take care of hte rest.

Yes, your method and SQL query are enough for checking. If there is no row output in the query, it will be null.

Related

Boolean method is returning true everytime

I'm using SQL to compare a date of an event
public static boolean sameDate(String DateString)
{
PreparedStatement statement = Application.database.newStatement("SELECT * FROM BookShift WHERE id = ? IN (SELECT id FROM Class WHERE Date = ?)");
try
{
if(statement !=null)
{
statement.setInt(1, main.id);
statement.setString(2, DateTwo);
ResultSet results = Application.database.runQuery(statement);
if (results != null)
{
return true;
}
else {
return false;
}
}
}
catch (SQLException resultsexception)
{
System.out.println("Database result processing error: " + resultsexception.getMessage());
}
return false;
}
Whenever I run my program and try booking a new shift, regardless of whether it does clash or not it always returns that it does.
You need to check if the result set has any rows or not, not check if it is null.
if (results.next())
{
return true;
}
else {
return false;
}
or, of course, just
return results.next();
As the comments say, it is not generally correct to check if results is null. I don't have the SQL experience to tell you what runQuery() will return on a query that fails, but I doubt that it's null, I would expect it to return an empty ResultSet.
Checking if it's null first isn't a bad thing, and in fact is a good idea to avoid NullPointerException throws. However, it's not enough to just use that check.

How do you determine if an insert or update was successful using Java and MySQL?

I am using Java to connect to a MySQL database. I am trying to insert or update data into the database.
Even though I am quite sure the insert was successful, it returns false.
According to the "execute" API, the return value is "true if the first result is a ResultSet object; false if it is an update count or there are no results".
How can I determine whether or not my insert or update was successful?
public boolean insertSelections(String selection, String name){
String sql ="INSERT INTO WORKREPORT VALUES (?,?,?,?,?)";
boolean action = false;
try {
PreparedStatement stmt = conn.prepareStatement(sql);
SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
String formatDate = dateFormat.format(new java.util.Date(System.currentTimeMillis()));
java.util.Date mDate = dateFormat.parse(formatDate);
java.sql.Timestamp timeStamp = new java.sql.Timestamp(System.currentTimeMillis());
// Date time= new Date(mDate.getTime());
stmt.setInt(1, Integer.parseInt(getNumberByName(name).trim()));
stmt.setString(2, name);
// stmt.setDate(3, time);
stmt.setTimestamp(3, timeStamp);
stmt.setString(4, selection);
stmt.setString(5, "N/A");
action = stmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return action;
}
Since you are using PreparedStatement you can call executeUpdate() -
int count = stmt.executeUpdate();
action = (count > 0); // <-- something like this.
From the Javadoc (Returns) link above, emphasis added,
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing.
If you want to insert a large number of entries, I would prefer addBatch() and executeBatch().
First of all this you should know :
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
int i = stmt.executeUpdate();
if (i > 0) {
System.out.println("success");
} else {
System.out.println("stuck somewhere");
}
Try this and check it out whether insert is happening or not
If you don't get a exception I think query is went ok.
Or, you might be able to use executeUpdate() (http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeUpdate() )
You can do a select count(*) do validate number of records if you want.
Try this, whether you want to know whether the data is inserted or not , if the record is inserted it return true or else false.
if(action > 0){
return true;
}else{
return false;
}

Java -> Mysql: get INT doesnt work?

In my DB theres a field named 'failcounter' and its an int.
Which query i have to use to receive the int?
i tried with:
SELECT `failcounter` FROM `randomstuff`
and tried to receive the int with:
if(zrs.next()){
return zrs.getInt(1);
}else{
return -99;
}
but im not able to get the int.
Whats wrong? =)
Here is the whole method, maybe theres something wrong:
public static int getFailCounter() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
PreparedStatement zpst=null;
ResultSet zrs=null;
zpst=connect.prepareStatement("SELECT `failcounter` FROM `randomstuff`");
zrs=zpst.executeQuery();
if(zrs.next()){
return zrs.getInt(1);
}else{
return -99;
}
}catch (Exception e) {
throw e;
} finally {
close();
}
}
From your comment I always get -99
It means that ,
if(zrs.next()){
return zrs.getInt(1);
}
doesnt gets executed . Also understand the differences using if(zrs.next()) and while(zrs.next())
You usually use "while" as you want to loop through all the data in the result set. You use "if" when the query returns one row by definition
So in your case the ResultSet must be null or the column index might be wrong . so check for the Data in the table first
Hope this helps !
Try you this.
ResultSet res = st.executeQuery("SELECT * FROM event");
while (res.next())
{
int id = res.getInt("id");
String msg = res.getString("msg");
System.out.println(id + "\t" + msg);
}
And follow more read [How to connect with MySQL database using Java
Read more: http://mrbool.com/how-to-connect-with-mysql-database-using-java/25440#ixzz30N93JAkm]1
Best of Luck!

Why won't this stored procedure call from Java work?

Here is my stored procedure:
CREATE OR REPLACE PROCEDURE VIEWBROKERS
(o_username OUT USERS.USERNAME%TYPE)
AS
BEGIN
SELECT USERNAME
INTO o_username
FROM USERS
WHERE Role_ID = 3 ;
END VIEWBROKERS;
Here is my method calling the stored procedure:
public ResultSet pullBrokers() {
ResultSet rs = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(Messages.getString("OracleUserManagement.0"), Messages.getString("OracleUserManagement.1"), Messages.getString("OracleUserManagement.2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String storedProcedure = "{call VIEWBROKERS(?)}";
CallableStatement statement = con.prepareCall(storedProcedure);
statement.registerOutParameter(1, java.sql.Types.VARCHAR);
rs = statement.executeQuery();
con.commit();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
And lastly when I tried to print out the results:
public class TEST {
public static void main(String[] args) throws SQLException{
OraclePullListOfUsers pull = new OraclePullListOfUsers();
ResultSet rs = pull.pullBrokers();
try {
while (rs.next()){
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I get the error message ORA-01422: exact fetch returns more than requested number of rows
Which is strange ,because there are only two rows of data in the table...
If someone could point me in the right the direction, that would be awesome!
Looks like you're problem is not related to Java, just on the SQL side. Could it be that both those two rows in the table have Role_ID=3?
The root cause for your problem:
ORA-01422: exact fetch returns more than requested number of rows
is that PL/SQL select into statement expects a query to match to exactly one row. If the query returns no rows or if the query return more than one row (as in your case) it will throw an exception.
You can't use select into to save the results to a single out variable if the query can return more than one row. Instead your subprogram should return a cursor (that is a pointer to a record set) that your Java component can query. Note that returning a cursor is not the only option, but in your case it looks like a good starting point.
This issue has been addressed several times in StackExchange universe. Please take a look e.g.
Return many rows on a plsql Oracle10g
How to return multiple rows from the stored procedure? (Oracle PL/SQL)
Calling Oracle PL/SQL stored procedure from java middle tier using JDBC on Linux?
A Java example Using Ref Cursors To Return Recordsets.

what is the value of resultset ,if query does not return any record?

public ResultObject takePrefixGroupId(ArrayList prefixGroupName)
{
debugLog(MODULE_NAME, "Inside the takePrefixGroupId() of LCRConfigurationSessionBean");
ResultObject resultObject = new ResultObject(LCRResponseCode.LCR_CONFIGURE_SEARCH_ERROR_EJB, null);
String strSelectQuery = null;
String strMessage=null;
ResultSet resSet = null;
Collection colInValideRecord =new ArrayList();
Collection colErrorMessage=new ArrayList();
Collection colValidRecord = new ArrayList();
Collection colDataValidation=null;
try{
for(int i=0;i<prefixGroupName.size();i++)
{
strSelectQuery = "select DESTINATIONGROUPID from TBLMDESTINATIONGROUP where NAME='"+prefixGroupName.get(i)+"'";
debugLog(MODULE_NAME, "Query::::::"+strSelectQuery);
resultObject = execute(strSelectQuery);
if(resultObject.getResponseCode() == LCRResponseCode.SUCCESS_RESPONSE_CODE)
{
resSet = (ResultSet)resultObject.getResponseObject();
debugLog(MODULE_NAME, "resSet::::::"+resSet);
if(resSet != null)
{
while(resSet.next())
{
colValidRecord.add(resSet.getString("DESTINATIONGROUPID"));
}
}
else
{
strMessage=LCRResponseCode.errorCodeToMessage(LCRResponseCode.PREFIX_GROUP_DOES_NOT_EXIST_ERROR);
debugLog(MODULE_NAME,"MESSAGE::: "+strMessage);
colErrorMessage.add(strMessage);
colInValideRecord.add(prefixGroupName);
debugLog(MODULE_NAME,"No Prefix Group is found.");
}
colDataValidation=new ArrayList();
colDataValidation.add(colValidRecord);
colDataValidation.add(colInValideRecord);
colDataValidation.add(colErrorMessage);
resultObject.setResponseObject(colDataValidation);
resultObject.setResponseCode(LCRResponseCode.SUCCESS_RESPONSE_CODE);
}
else
{
debugLog(MODULE_NAME, "Unable to execute search query for in searchDestination() of LCRConfigurationSessionBean.");
resultObject.setResponseCode(LCRResponseCode.LCR_CONFIGURE_SEARCH_ERROR_EJB);
}
}
}
catch(Exception e)
{
e.printStackTrace();
errorLog(MODULE_NAME, "exception in searchDestination() of LCRConfigurationSessionBean");
resultObject.setResponseCode(LCRResponseCode.LCR_CONFIGURE_SEARCH_ERROR_EJB);
resultObject.setException(e);
}
return resultObject;
}
this is the code
According to the javadoc, Statement.executeQuery() never returns null. So the answer is a ResultSet with no rows.
You can tell that the ResultSet is empty if next() returns false the first time you call it.
You may also be able to tell by calling the optional isAfterLast() method. If it is supported, this method will give you an answer without advancing the cursor as a side-effect.
I've no idea what the answer would be for your code, since you are calling an execute method whose implementation you have not provided.
ResultSet executeQuery(String sql)
throws SQLException Executes the given SQL
statement, which returns a single
ResultSet object.
Parameters: sql - an SQL statement to be sent to the database, typically
a static SQL SELECT statement
Returns: a ResultSet object that contains the data produced by the
given query; never null
Throws: SQLException - if a database access error occurs, this
method is called on a closed Statement
or the given SQL statement produces
anything other than a single ResultSet
object
Statement
Also you can do it like:
if(resSet.last().getRow() > 0)
{
resSet.first();
while(resSet.next())
{
colValidRecord.add(resSet.getString("DESTINATIONGROUPID"));
}
}
else
{
//...

Categories

Resources