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

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.

Related

How do I filter search by entering all the column data on java-sql application?

I've been trying to solve this issue for the past couple of days. I have a SerachUser function where I input all the data like age, gender, city and interests into each string and check them into a select query command.
If data is present, I print them out.
Unfortunately the search isn't working completely. For eg: my table user doesn't have 'F' gender. But if I type 'F' I still get data instead of displaying "ResultSet in empty in Java".
Below is a brief code I have done.
try{
conn = DriverManager.getConnection(DB_URL,"shankarv5815","1807985");
st = conn.createStatement();
rs = st.executeQuery("Select loginID, f_name, l_name from users where gender = '" +
searchUser.getGender() + "' and age between '" + min + "' and '" + max + "' and city = '" +
searchUser.getCity() + "' and interest1 = '" + searchUser.getInterest1() +
"' or interest2 = '" + searchUser.getInterest1() + "' or interest3 = '" +
searchUser.getInterest1() + "' and loginID != '" + curUser + "'");
if (rs.next() == false) {
System.out.println("ResultSet in empty in Java");
}
else {
do {
String id = rs.getString(1);
String fName = rs.getString(2);
String lName = rs.getString(3);
System.out.print(id +" ," + fName + ", " + lName);
System.out.println();
} while (rs.next());
}
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
try
{
conn.close();
st.close();
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
A reduced version of your query is :
Select * from users
Where gender = 'F'
And interest1 = 'FISHING'
Or interest2 = 'FISHING'
However, AND has higher priority than OR, so this query is equivalent to :
Select * from users
Where ( gender = 'F' And interest1 = 'FISHING')
Or interest2 = 'FISHING'
What you need to do is add brackets, so :
Select * from users
Where gender = 'F'
And ( interest1 = 'FISHING' Or interest2 = 'FISHING')
By the way, you are also leaving yourself wide open to a SQL injection attack, by including the search terms directly in the SELECT statement ( see What is SQL injection? ).
Much better would be to get in the habit of always using a PreparedStatement.

How can I check if the query is empty?

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

Defaults if player doesn't already have gems

Follow up question from here
Here is my current code, I try to preform the check to see if they have any tokens and then set the tokens if they dont but it seems to just be running the code no matter if I set it or not.
#EventHandler
public void onJoin(PlayerJoinEvent event) throws SQLException {
Player player = event.getPlayer();
String name = player.getName();
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
res.next();
int tokens = 0;
if (res.getString("PlayerName") == null) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}
player.sendMessage(tokens + " Tokens.");
}
The way you check for a row's existence is wrong. Take a look at your query:
"SELECT * FROM tokens WHERE PlayerName = '" + name + "'
If a player does not exist in the table, this query will return 0 rows, not a row with null for the player's name, like you're checking now. Instead, you should check if the ResultSet has a row:
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
int tokens = 0;
if (res.next()) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}

Dynamic database and SQL queries

This is what i need to create.
I have a web site where the user can come and design an application form according to their need/requirement. Basically there is a HTML designer available in the website to perform this action. The user can drag and drop HTML components which in turn creates an application form in pure HTML. For example, for creating the "Personal Section" the user can drag & drop the label component and TextBox component and put the label text as "FirstName" and so on. I need to have a database created according to the form the one user has created. If he created the personal section with only FirstName and LastName the table created should have only those two cols. (ie, its up to the user to decide on col name at the time of form creation, the SQL queries for inserting and Updating DB fields all should perform dynamically). Please help me to solve this issue. Any suggested pattern there to apply? (The web application is created using Java)
Any help will be appreciated greatly
Thanks
You may need to code for some sort of form builder which builds the form on the fly and can take help from following code to create dynamic sql tables. This is just a hint not the perfect solution for your problem
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "123");
Statement st = con.createStatement();
System.out.println("connection has been made ");
Scanner scanner = new Scanner(System.in);
System.out.println("please enter table name ");
String tableName = scanner.next();
String strr = null;
System.out.println("Enter no of columns you like to use: ");
int noc = scanner.nextInt();
for (int i = 1; i <= noc; i++) {
BufferedReader bf = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Enter column name with type ");
String s1 = bf.readLine();
if (strr == null) {
strr = s1;
} else {
strr = strr + s1;
}
}
st.executeUpdate("create table " + tableName + "(" + strr + ")");
System.out.println("your table " + tableName
+ " has been created!!!");
ResultSet rs = st.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
System.out.println("Number of Columns of your table =" + tableName
+ " " + NumOfCol);
System.out.println("Column names are ");
for (int i = 1; i <= NumOfCol; i++) {
System.out.println(rsmd.getColumnName(i));
}
String strn = null;
System.out.println("please enter values you need to insert");
for (int i = 1; i <= NumOfCol; i++) {
String s5 = scanner.next();
if (strn == null) {
strn = s5;
} else
strn = strn + s5;
}
System.out.println(strn);
st.executeUpdate("insert into " + tableName + " values" + "("
+ strn + ")");
System.out.println("your table " + tableName
+ " has been filled!!!");
con.close();
System.out.println("connection has been colsed ");
}
catch (Exception e) {
System.out.println(e.getMessage());
}

error in java update

if (e.getSource() == btn_updt) {
try {
String str = "img";
int max_avail;
double price;
Frame f = new Frame();
Connection con;
DriverManager
.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:dsnproj", "", "");
Statement s = con.createStatement();
// int mno=Integer.parseInt(txt_contcno.getText());
price = Double.parseDouble(txt_price.getText());
max_avail = Integer.parseInt(txt_qty_avl.getText());
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',desc='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";
System.out.println(qry_up);
s.execute(qry_up);
System.out.println("updated");
// JOptionPane.showMessageDialog(f,
// "Updates Successfully : ","A plain message",JOptionPane.PLAIN_MESSAGE);
} catch (Exception ae) {
System.out.println(ae.getLocalizedMessage());
}
return result;
}
and i got error as:
update category set prod_name='jjhhj',desc='jjjh',photo='img',max_quan_avail=88,cur_price=99.0,per='piece' where p_name='brush' [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
please help me...
Since DESC is a keyword, you must surround it with [].
Use this for your query:
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',[desc]='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";

Categories

Resources