Sql statement Java between 2 tables and 2 values ( variables) - java

i am trying to do the following and it doesnt accept it.
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ="' + cu_ID + "'";
select from two tables and two values( variables)

Try this:
String sql_eco = "select * +
from orders +
where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";
^

Try, assuming CustomerID and EmployeeID are both Integer column type
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID =" + cu_ID;

Use this. you have misplaced " for CustomerId
String sql_eco = "select * from orders where EmployeeID=" +e_ID + " and CustomerID ='" + cu_ID + "'";

values variable u wanna say something like this?
String sql_eco = "select * +
from orders +
where 1=1 ";
if(e_ID != null) {
sql_eco += " AND EmployeeID=" +e_ID ;
}
if(cu_ID != null){
sql_eco += " and CustomerID ='" + cu_ID + "'";
}
to improve this code u can use stringbuilder/stringbuffer

Related

SQL Query - FindCostumerWithHighestBill

I am try to find the costumer with the highest bill using this sql that I wrote , but apparently I run into this error :
Every derived table must have its own alias
This is what I wrote:
public static void findCustomerWithHighestBill(Connection c) throws SQLException {
String query = "SELECT CustomerID, CustomerName, CITY, sum(sum_all) As 'data'\r\n"
+ "FROM (SELECT *, sum(Price) As 'sum_all'\r\n"
+ " FROM (SELECT *, Customer.NAME AS \"CustomerName\"\r\n"
+ " FROM Transactions\r\n"
+ " INNER JOIN Product ON Product.ID = Transactions.ProductID\r\n"
+ " INNER JOIN Customer ON Customer.ID = Transactions.CustomerID)\r\n"
+ " GROUP BY CustomerID, ProductID\r\n"
+ " ) \r\n"
+ "GROUP BY CustomerID\r\n"
+ "ORDER BY data DESC";
Statement statement = c.createStatement();
ResultSet set = statement.executeQuery(query);
set.next();
System.out.println("CustomerID: " + set.getInt("CustomerID") +
", Name: " + set.getString("CustomerName") + ", City: " +
set.getString("CITY") + ", Bill: " + set.getFloat("data"));
}
Can please somoane help me zith this ?
Coming back ,
It seems that indeed ad most of you says in the comments I should identify my tables first but, apparently I also have miss to avoid the duplicate ID column.
Here goes my new query:
String query = "SELECT CID, CustomerName, City, sum(sum_all) As data" +
" FROM (SELECT *, sum(PPROD) As sum_all" +
" FROM (SELECT Product.ID as PID,Customer.ID as CID,Product.Price as PPROD,City, Customer.NAME AS CustomerName" +
" FROM Transactions" +
" INNER JOIN Product ON Product.ID = Transactions.ProductID" +
" INNER JOIN Customer ON Customer.ID = Transactions.CustomerID) As t2" +
" GROUP BY CID, PID" +
" ) As t1" +
" GROUP BY CID" +
" ORDER BY data DESC;";

Unknown column 'ROWNUM' in 'where clause'

I read a lot of topics about this problem but most of them were having problem with some complex (at least for me) code;
I have followed the oracle ROWNUM Pseudocolumn guide but when I write
SELECT * FROM " + tableName + "
WHERE ROWNUM < 12;
I get this error:
Unknown column 'ROWNUM' in 'where clause'
I then tried to do like the solution suggested here Select where row number = rownum
but nothing changes.
My code looks like this:
sql = "SELECT C.* "
+ "FROM ( SELECT * "
+ " FROM " + tableName + " ) C "
+ "WHERE C.ROWNUM < 12;";
resultSet = statement.executeQuery(sql);
You can refer http://www.w3schools.com/sql/sql_top.asp.
ROWNUM is used in Oracle. Assuming you are using MySQL as you have tagged your question to MySQL.
You can change ROWNUM with limit clause
SELECT * FROM " + tableName + "
LIMIT 11;
Use the below
sql = ""
+ "SELECT C.*,ROWNUM as RECNUM "
+ "FROM ( "
+ " SELECT * "
+ " FROM " + tableName + " ) C "
+ "WHERE C.RECNUM < 12;";
resultSet = statement.executeQuery(sql);
Try this it will helpful for ur problem:
select * from (select * from " + tableName + ") "WHERE C.ROWNUM < 12;
Try this : [if you use mysql]
sql = ""
+ "SELECT C.* "
+ "FROM ( "
+ " SELECT * "
+ " FROM " + tableName + " ) C "
+ "LIMIT 11;";
resultSet = statement.executeQuery(sql);
For sql server :
SELECT TOP 12 ...

Getting back movie ratings excluding my own

Basically, I have a table called ratings with 3 columns FILM, EMAIL, and RATING in mysql.
I can get back the average rating for all the films, but I must then display the ratings
of the movies that I haven't already rated , so I must only display all the films everybody else rated except me.
String email = Main_Login.accounttext.getText().trim();
statement = (PreparedStatement) con
.prepareStatement(""
+ "SELECT FILM,(film_total_ratings/number_of_ratings) as ratings_rating "
+ "FROM( "
+ "SELECT COUNT(*) as number_of_ratings, FILM, "
+ " SUM(RATING) as film_total_ratings "
+ " FROM ratings GROUP BY film "
+ "ORDER BY rating DESC"
+ ") TMP_Film");
result = (ResultSet) statement.executeQuery();
int i = 0;
while (result.next() && i <= 4) {
i++;
// if (result.getString(1).contains(email)) {
System.out.println((i) + ")" + " " + "[Movies You Might Like]"
+ " " + result.getString(1) + " " + "[Rating]" + " "
+ result.getString(2));
You may try to use CASE to add a column indicating that movie has been rated by the respective email or not. This is not tested but you may get the concept:
statement = (PreparedStatement) con
.prepareStatement(""
+ "SELECT FILM,(film_total_ratings/number_of_ratings) as ratings_rating "
+ "FROM( "
+ "SELECT COUNT(*) as number_of_ratings, FILM, "
+ " SUM(RATING) as film_total_ratings, "
+ " SUM(CASE WHEN EMAIL LIKE '%"+email+"%' THEN 1 ELSE 0 END) as rated"
+ " FROM ratings GROUP BY film HAVING rated=0 "
+ "ORDER BY rating DESC"
+ ") TMP_Film");

Having Syntax Error in code java

Why is there a syntax error in this code?
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num + ","
+ "Email = '" + email_add + "',"
+ "Address = '" + mail_add + "',"
+ "SurveyStatus = " + radio_group + ","
+ "Subscription = " + receive_info +
"WHERE membership_ID = '" + member_ID';
I thought my code was right.
If it is the error in your code, check all the variables that you have used are declared and initialized with proper values.
If it is the syntax of the sql that is bothering you , here is what your sql would look like if all the variables are initialized to null.
UPDATE Customers SET (Contact)null,Emailnull,Address,null,SurveyStatus,null,SubscriptionnullWHERE MembershipID =null
Use spaces in your strSqlUpdate to correct the above sql.
EDIT
What you need is something like this.
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num
+ ",Email = '" + email_add + "'"
+ ",Address = '" + mail_add + "'"
+ ",SurveyStatus = '" + radio_group + "'"
+ ",Subscription = '" + receive_info + "' "
+ "WHERE membership_ID = '" + member_ID + "'";
I get no syntax errors when I declare and Initialize all of the variables. You have to make sure they're all initialized, within the scope of the strSqlUpdate
String contact_num = "";
String email_add = "";
String mail_add = "";
String radio_group = "";
String receive_info = "";
String member_ID = "";
String strSqlUpdate = " UPDATE Customers SET (Contact)" + contact_num + "," + "Email"
+ email_add + "," + "Address" + "," + mail_add + "," + "SurveyStatus" + "," + radio_group
+ "," + "Subscription" + receive_info + "WHERE MembershipID =" + member_ID;
Also considering you're talking about SQL syntax, adding on to what others have said, I'd advise you should use a PreparedStatement to avoid SQL injection.
PreparedStatement pst = conn.prepareStatement(
"UPDATE Customers SET (Contact) ?, ?, ?, ?, ?, ?, ? WHERE ? = ?");
pst.setString(1, contact_num);
pst.setString(2, email_add);
... and so on
An error in your current SQL syntax is this
"Subscription" + receive_info + "WHERE MembershipID
Translated as
"...Subscrptionreceive_infoWHERE MembershipID..."
You need to add spaces wherever you don't have commas

nested if for sql results

Guys I am struggling to create search queries for a database I am developing but the user choices are so many! I don't know how to filter them out! Do I have to create a different query for EVERY SINGLE choice the user checks? If he wants to search for name only, that's an other query. Name and surname is an other. Age and country is another! I don't know how to do that without writing hundreds of lines of code! I have tried this example but it only works if the user fills every textfield.
private void searchB_actionPerformed(ActionEvent e) {
query = "SELECT agent_id, name, surname, clearance, user_id, alias, missions, age, country, current_mission FROM agents WHERE " ;
if (!agentidTF.getText().isEmpty()) {
query = query + "agent_id = '" + agentidTF.getText() + "' ";
//System.out.println(query);
if (!nameTF.getText().isEmpty()) {
query = query + " AND name = '" + nameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!surnameTF.getText().isEmpty()) {
query = query + " AND surname = '" + surnameTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (clearancebox.getSelectedItem() != "SELECT CLEARANCE") {
query =
query + " AND clearance = '" + clearancebox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
if (!useridTF.getText().isEmpty()) {
query = query + " AND user_id = '" + useridTF.getText() + "' ";
//System.out.println(query);
if (!ageTF.getText().isEmpty()) {
query = query + " AND age = '" + ageTF.getText() + "' ";
//System.out.println(query);
if (!aliasTF.getText().isEmpty()) {
query = query + " AND alias = '" + aliasTF.getText().toUpperCase() + "' ";
//System.out.println(query);
if (!currmissTF.getText().isEmpty()) {
query =
query + " AND current_mission = '" + currmissTF.getText().toUpperCase() +
"' ";
//System.out.println(query);
if (countrybox.getSelectedItem() != "SELECT COUNTRY") {
query =
query + " AND country = '" + countrybox.getSelectedItem().toString().toUpperCase() +
"' ";
//System.out.println(query);
} //end of countrybox
} //end of currmissTF
} //end of aliasTF
} //end of ageTF
} //end of useridTF
} //end of clearancebox
} //end of surnameTF
} //end of nameTF
} //end of agentidTF
query = query + " ORDER BY agent_id";
System.out.println("ACTUALL QUERY IS: " + query);
}

Categories