How can I check if the query is empty? - java

I want to move to the other frame if the query result is empty. How can I check if the query is empty?
String query2 ="Select* from biletbilgileri where FilminÄ°smi='" + filmKoltuk + "'" +
" " + "and" + " " + "SeansTarihi='" + SeansTarihKoltuk + "'" + " " + "and" + " " +
"SeansSaati='" + SeansSaatKoltuk + "'";
Statement stmt1=conn.createStatement();
ResultSet rs1=stmt1.executeQuery(query2);
rs1.next();
if(rs1==null)
{
tesekkurEkrani1.setVisible(true);
tesekkurEkrani1.setSize(1000,500); }
else {
JOptionPane.showMessageDialog(null, "This chair isn't empty!");
}

You want to use SQL count(*) in the query select count(*) from biletbilgileri .... If the returned value is 0, there are no rows returned by your original query.
String query2 = "select count(*) from biletbilgileri ...";
ResultSet rs1 = stmt1.executeQuery(query2);
rs1.next();
int count = rs1.getInt(1);
if (count == 0) {
// empty
}

When you call rs1.next();, it returns a boolean. If the boolean is false, it means there are no more rows. so I think you want to do this:
boolean notEmpty = rs1.next();
if(notEmpty )
{

Related

no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

Log Cat:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
code:
102) public String getID(String note){
103) SQLiteDatabase db = this.getWritableDatabase();
104) String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
105) db.rawQuery(query,null);
106) return query;
107) }
I do have a column name hey in my Database
Database Picture
Your terminology is confused.
hey is a value, NOTEMEMOS is a column.
You need to quote the value hey to let the SQL compiler know that it is a string value, rather than a column you are trying to compare against.
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'");
Just a note, you would be better off using a parameterised query, as using raw values is insecure (see SQL injection).
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?"); // That's right, quotes aren't needed for a parameterized query.
String result = "";
Cursor cursor = db.rawQuery(query,new String[] {note} );
if (cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(COL_0));
}
cursor.close();
return result;
Your query should look like this
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = 'hey'
Let me know if it helps
The way that you concatenate the parameter note creates this sql statement:
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
so hey is considered a column identifier and not a string literal because it is not enclosed inside single quotes.
You could do this instead:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'";
and it would work.
But the recommended way is passing parameters as a string array like this:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {note});
return cursor;
This way you don't worry about single quotes as this is taken care of by rawQuery().
I guess you want to return the Cursor object and not the sql query string, right?

How to convert a statement into PreparedStatement in JAVA

i like to change the old one into new and my old sql query its in statement and i like to change into prepared statement . how could i change ?
for example :
*
strSql = "SELECT Id as GroupId, Name,Description FROM Groupcodes WHERE deleteFlag=0 and GroupType = '" + StrGroupType + "' ";
if(strSearchBy.length() > 0 && strSearchText.length() > 0)
{
if(strSearchOption.equalsIgnoreCase("Starts With")) {
strSql += " AND " + strSearchBy + " LIKE '" + strSearchText + "%' ";
}
else if(strSearchOption.equalsIgnoreCase("Contains")){
strSql += " AND " + strSearchBy + " LIKE '%" + strSearchText + "%'" ;
}
}
strSql += " ORDER BY Name ASC";
if( nCounter > 0 ) {
strSql += " LIMIT " + (nCounter - 1) + ", " + nMaxCount;
}
*
once you teach for this example then i will do for upcoming codes .
You do it like this:
PreparedStatement mStatement = getDBTransaction().createPreparedStatement("select * from test_table where user_id = ?", 0);
mStatement.setString(1, "4913");
ResultSet rs = mStatement.executeQuery();
The '?' character parametizes the query and later u set its value using setString. Note in the setstring function the first parameter is indicated by index 1 (not 0 ). Also note u dont need ' ' if your where condition is comparing varchars

java - after search of database, print the full row of the result

I got a code, which is searching a whole database. Everything works fine, the only problem is, that I would like to post the whole tuple with integers and chars and so on.
package src;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.regex.Pattern;
/*
PATTERN MATCHING
*/
public class BigSearch {
public static void main(String[] args) {
try {
String keyword;
String schema = "public";
Boolean caseAware = true;
System.out.println("Insert the term we shall look for in the database.");
Scanner s = new Scanner(System.in);
keyword = s.nextLine();
System.out.println("Do you want the search to be case sensitve "
+ "\n1 - case sensitive"
+ "\n0 - case insensitive");
int caseAwareInt = s.nextInt();
while (caseAwareInt != 0 && caseAwareInt != 1) {
System.out.println("You need to enter 1 or 0. Enter again!");
caseAwareInt = s.nextInt();
}
if (caseAwareInt == 1) {
caseAware = true;
} else if (caseAwareInt == 0) {
caseAware = false;
}
System.out.println("Your search is now case ");
if (caseAware) {
System.out.println("sensitive!");
}
if (!caseAware) {
System.out.println("insensitive!");
}
String like = "";
if (caseAware) {
like = "LIKE";
} else {
like = "ILIKE";
}
Connectivity connectivity = new Connectivity();
conn = connectivity.getConnection();
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
Statement stmt5 = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
ResultSet tablenames = stmt2.executeQuery("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
rs.next();
int counttables = rs.getInt(1);
System.out.println("Tabellen im Schema: " + counttables);
int appearance = 0;
int diftables = 0;
for (int i = 0; i < counttables; i++) {
tablenames.next();
ResultSet columnnames = stmt3.executeQuery("SELECT * " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
ResultSet rss = stmt4.executeQuery("SELECT COUNT(*) " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
rss.next();
int countcolumns = rss.getInt (1);
System.out.println("Spalten in der Tabelle " + tablenames.getString(1) + ": " + countcolumns);
int count = 0;
for (int i2 = 0; i2 < countcolumns; i2++) {
columnnames.next();
columnnames.getString(1);
System.out.println("Spaltenname: " + columnnames.getString(1));
System.out.println("Tabelle: " + tablenames.getString(1));
ResultSet containsString;
containsString = stmt5.executeQuery("SELECT * "
+ "FROM " + tablenames.getString(1)
+ " WHERE " + columnnames.getString(1) + " " + like + " '%" + keyword + "%'");
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
}
if (count > 0) {
diftables ++;
}
}
System.out.println("The keyword was found " + appearance + " times in " + diftables + " different tales.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I think the problem is the following code:
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
So there I am saying getString(1), but I would like to print the full row and because all table have different variable types and different numbers of it, I can't say getString 1, 2, 3, and so on. .getRow doens't work is well.
Any ideas?
There is no way to get all values at once. You need to get them yourself column-by-column. You could use getObject and let the default toString() of that object handle it. The other option is to use the ResultSetMetaData to get the right type of processing, but this might be too complex for your needs.
The getRow doesn't work, because it "Retrieves the current row number.".
Some JDBC drivers will support getString for most datatypes and handle the conversion for you.

Insert query - executeUpdate returning -1

I am trying to insert records into SQL Server using jdbc conn (in java).
I am able to insert into SQL, if I manually copy the query statement in the java file. But its not inserting from the code?
Please help, where am I committing mistake?
PreparedStatement preparedStatement = null;
if (conn != null) {
System.out.println("Connection Successful!");
}
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
//Result Set for Prouduct Table
ResultSet rs = sql_stmt.executeQuery("SELECT MAX(ID), MAX(RG_ID), MAX(WG_ID) FROM " + strDBName + ".[dbo].Product");
if ( rs.next() ) {
// Retrieve the auto generated key(s).
intID = rs.getInt(1);
intRG_ID = rs.getInt(2);
intWG_ID = rs.getInt(3);
}
for (int iCount = 0 ;iCount < arrListLevel_1_Unique.size(); iCount++)
{
//Result Set for Prouduct Table
sql_stmt_1.executeUpdate("\n IF NOT EXISTS(SELECT 1 FROM " + strDBName + ".[dbo].Product WHERE [Name] NOT LIKE '" + arrListLevel_1_Unique.get(iCount) + "') "
+ "\nINSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ "VALUES ( '" + arrListLevel_1_Unique.get(iCount) + "',"
+ + (intWG_ID + intRowIncrement) + ", " + (intWG_ID + intRowIncrement + 1) + ", 5828)");
intRowIncrement++ ;
}
rs.close();
sql_stmt.close();
sql_stmt_1.close();
//Close the database connection
conn.close();
You have two plus signs + in the fifth row:
+ + (intWG_ID + intRowIncrement) + ...
Otherwise, the problem may lie in the IF ... statement. You can try this instead:
sql_stmt_1.executeUpdate(
" INSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ " SELECT '" + arrListLevel_1_Unique.get(iCount) + "',"
+ (intWG_ID + intRowIncrement) + ", "
+ (intWG_ID + intRowIncrement + 1) + ", 5828 "
+ " WHERE NOT EXISTS( SELECT 1 FROM " + strDBName
+ ".[dbo].Product WHERE [Name] LIKE '"
+ arrListLevel_1_Unique.get(iCount) + "') "
) ;
I think the problem lies on the "\n", have you tried eliminating those 2 of "\n" and see if it's working?
Actually this kind of implementation (building SQL string with string concatenation) is really bad. At first is prone to SQL injection, and then secondly you will have problem if the value to be inserted contains character single quote or ampersand.
Instead, you should use "prepare statement".
And it's tidier to store the SQL string into a variable before executing it. So that you can log it (for debug purpose), roughly something like this:
String sqlCommand = "select * from " + tableName;
System.out.println(sqlCommand);
sqlStatement.executeUpdate(sqlCommand);
P.S. it is not advised to use system.out.println for debug, you should implement a proper logging system.

mysql select query in java

I'm new to connecting java with a mysql database. What's wrong with my query here:
PreparedStatement statement = conn.prepareStatement("SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'");
In your statement " ... q_table.QID='" + number_input + "' AND ... the variable number_input is enclosed in a single quote ('). This is used for string lieterals. If you remove the single quote it should work:
String prest= "SELECT * FROM q_table, choices, answers WHERE questions.QID=? AND choices.CID=? AND answers.AID=?";
prest.setInt(1,1980);
prest.setInt(2,2004);
.
.
ResultSet rs = prest.executeQuery();
while (rs.next()){
String mov_name = rs.getString(1);
int mov_year = rs.getInt(2);
count++;
System.out.println(mov_name + "\t" + "- " + mov_year);
}
System.out.println("Number of records: " + count);
prest.close();
con.close();
Well, the first problem is that you're opening yourself up to a SQL injection attack by including values directly in your SQL. Use a parameterized query instead.
Now we can't really tell what's wrong beyond that, although the fact that you're quoting a number seems suspicious, as does the fact that you're using the same value for a question ID, a choice ID and an answer ID. That seems unlikely to be appropriate.
If you could give us more information about what's happening vs what you expected to happen, that would really help.
When you use prepared statements, you can't set the values there.
You have to first prepare the statement using question marks and then set the parameters later.
Here is an example:
public void updateCoffeeSales(HashMap<String, Integer> salesForWeek) throws SQLException {
PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;
String updateString = "update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement = "update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
updateSales.close();
updateTotal.close();
con.setAutoCommit(true);
}
}
SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'"
or
SELECT * FROM questions, choices, answers WHERE questions.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'"
That is not a proper prepareStatement. It's a concatenated query that will only lead you to sql injection horrors. Look here

Categories

Resources