Method to get the placement of a player with MySQL Query - java

I`ve a Problem with a SQL Query. I want to develop a Minecraft Plugin. The Plugin contains a Statistic. I want to create a Ranking in the Statistic. The player who have the most kills is on the first place and so on.. I created a Method which calculate your placement. First the SQL Query sort the tabel and than it looks in which your you are.
PreparedStatement ps = MySQL.getConnection().prepareStatement("SELECT * FROM (SELECT #r := #r+1 as pos, kills. * FROM kills, (SELECT #r := 1) tmp ORDER BY Kills DESC) WHERE UUID = ?");
ps.setString(1, uuid.toString());
ResultSet rs = ps.executeQuery();
The Error is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE UUID = '37bb2c2c-e170-469c-a08e-6a22e7d083cd'' at line 1
I dont know what the Error is.

You can't use user variables in a JDBC MySQL query. Here is one workaround for the query:
SELECT *,
1 + (SELECT COUNT(*) FROM kills k2 WHERE k2.Kills > k1.Kills) AS pos
FROM kills k1
WHERE UUID = ?
If you are using MySQL 8+, then analytic functions are a better way to go:
SELECT *, ROW_NUMBER() OVER (ORDER BY Kills DESC) pos
FROM kills
WHERE UUID = ?
You may want to instead use RANK or DENSE_RANK. Note that the first correlated subquery approach is technically returning a rank, not a row number, in the event that two or more records be tied for the number of kills.

Related

Printing oracle sql Statement output in java eclipse console not working

I have a problem. I would like to implement a SQL Statement, into java and print it out in the console. When I do so, it gives me the wrong line or just a number:
So my Java code is this:
ConnectTodb daba = new ConnectTodb("password");
daba.connect();
System.out.println(db.getStatement().executeUpdate("SELECT * FROM (select entry, row_number() over(order by entrie_date desc) rn from entry) where rn = 1"));
When I perform this, it just prints the number 0 or sometimes 1. That makes no sense because the numbers in my database are different ones (like 8800 or 110200.23).
When I perform the same command (SELECT * FROM (select entry, row_number() over(order by entrie_date desc) rn from entry) where rn = 1) in my oracle sql Developer, it gives me the right number...

Java Regex: To know the number of rows to be returned by a SQL Query

I have a SQL query and I want to know how many rows will that SQL query return. Now the problem is that I want to know the number of results beforehand which means before running the SQL query.
I would have done this easily by ResultSet.getRow() to get the total number of rows from resultset. But as per the requirement, I can get the resultset only after knowing the number of rows to be returned by that query.
I tried the below Java Regex to solve the issue:
String orgQuery = "select * from emp where id<1210 and salary>55000;"
Pattern p= Pattern.compile("(?:)from\\s+(.*)*" , Pattern.CASE_INSENSITIVE);
Matcher m= p.matcher(orgQuery);
if (m.find()) {
countQuery = "SELECT COUNT(*) as total "+ m.group(1);
System.out.println(countQuery);
}
This work perfectly file and I get the "countQuery" as:
SELECT COUNT(*) as total from emp where id<1210 and salary>55000
By this I can easily know the number of rows to be returned beforehand but the problem occurs when my query become more complex like these two:--
even more complex in case of nested queries i.e. #query2.
#query1: select * from emp where id<1210 and salary>55000 order by dept, salary desc;
#query2: select name from emp where id IN (select id from emp where id < 1210 group by salary , id order by id ASC limit 10) order by id DESC limit 10
I think the main issue is with "Order By" clause. I can remove the "Order By" clause too by below regex:
Pattern.compile("(?:)from\\s+(.*)*" , Pattern.CASE_INSENSITIVE);
But it becomes more complex in case of Nested queries.
Can any Java Regex expert help????? I am using postgres as DB.
Wrap your existing query like so:
select count(*) from (<existing query>)
With your given example:
String orgQuery = "select * from emp where id<1210 and salary>55000";
String countQuery = "select count (*) from (" + orgQuery + ')';
I know this works with Oracle. I have not used postgres, so I am not certain if there would be anything preventing this approach from working there.
I will caution on this idea of getting a count first, however, that it might be possible for the data to change between your execution of the count and the actual query.

Detect, delete empty columns and update database in sql, oracle

I have 100 of columns and some of the doesn't have any values inside(they are empty) how can I search for empty columns and delete from table and update database? I tried this query but it doesnt work. It shows 0 rows selected. After selecting how can I update the database?
select table_name, column_name
from all_tab_columns
where table_name='some_table'
and column_name is NULL;
Thanks,
You are querying a data dictionary view. It shows meta-data, in formation about the database. This view, ALL_TAB_COLUMNS, shows information for every column of every table (you have privileges on). Necessarily COLUMN_NAME cannot be null, hence your query returns no rows.
Now what you want to do is query every table and find which columns have no data in them. This requires dynamic SQL. You will need to query ALL_TAB_COLUMNS, so you weren't completely off-base.
Because of dynamic SQL this is a programmatic solution, so the results are displayed with DBMS_OUTPUT.
set serveroutput on size unlimited
Here is an anonymous block: it might take some time to run. The join to USER_TABLES is necessary because columns from views are included in TAB_COLUMNS and we don't want those in the result set.
declare
dsp varchar2(32767);
stmt varchar2(32767);
begin
<< tab_loop >>
for trec in ( select t.table_name
from user_tables t )
loop
stmt := 'select ';
dbms_output.put_line('table name = '|| trec.table_name);
<< col_loop >>
for crec in ( select c.column_name
, row_number() over (order by c.column_id) as rn
from user_tab_columns c
where c.table_name = trec.table_name
and c.nullable = 'Y'
order by c.column_id )
loop
if rn > 1 then stmt := concat(stmt, '||'); end if;
stmt := stmt||''''||crec.column_name||'=''||'
||'to_char(count('||crec.column_name||')) ';
end loop col_loop;
stmt := stmt || ' from '||trec.table_name;
execute immediate stmt into dsp;
dbms_output.put_line(dsp);
end loop tab_loop;
end;
sample output:
table name = MY_PROFILER_RUN_EVENTS
TOT_EXECS=0TOT_TIME=0MIN_TIME=0MAX_TIME=0
table name = LOG_TABLE
PKG_NAME=0MODULE_NAME=0CLIENT_ID=0
PL/SQL procedure successfully completed.
SQL>
Any column where the COUNT=0 has no values in it.
Now whether you actually want to drop such columns is a different matter. You might break programs which depend on them. So you need an impact analysis first. This is why I have not produced a program which automatically drops the empty columns. I think that would be dangerous practice.
It is crucial that changes to our database structure are considered and audited. So if I were ever to undertake an exercise like this I would alter the output from the program above so it produced a script of drop column statements which I could review, edit and keep under source control.

java prepared statement

I have a requirement like this...
Need to execute a java prepared statement example:
String sql = "select first_name from student where roll_no :=1";
connection.prepareStatement(sql);
But the problem is, sometimes there can be NO rows in the table for the above query.
In that case, I want to query the 2nd table say student2. Hence the sql query will be now:
String sql2 = "select first_name from student2 where roll_no :=1";
Is there a way to achieve this condition of selecting from another table(student2) in a single sql query.
I want something like this pseudo code:
String sql = "if student1 table doesn't have a roll_num, then query student2 table";
Create a database procedure which you call with the prepared statement
MySql,
Oracle.
Hope this helps
Though your design is not good, I am giving hint to achieve what you are asking. When you execute first query, just check are there any result sets available, if not then execute second query.
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
In If block you need to execute second query.
Note: First rethink your design, if not possible. This solution works, a lame solution for lame problem :)
I think you could use e.g. UNION as:
select val from (select 'A' as val from DUAL
union
select 'B' as VAL from DUAL)
where rownum = 1;
but #tbraun89 is right think on your DB structure first

Eliminating quotes in prepared statement in mysql n java

I have a prepared statement like this
stmt = select * from table_name where id IN (?);
Once I pass the parameters the stmt looks like way
stmt = select * from table_name where id IN ('1,2,3');
There is no error while executing the query. However the resultset is returned only for the id=1. Is there some way I can eliminate the quotes / get the resultset for all these id's.
stmt = select * from table_name where id IN (?);
select GROUP_CONCAT(id) id from table ;
if(rs.next()){
stmt.setString(1,rs.getString("id"));
stmt.executeQuery();
}
Thanks in advance.
It's not clear what the ID type is, but I believe you should actually be preparing a statement with each possible value as a separate parameter:
select * from table_name where id IN (?, ?, ?)
Then add the three values for the three parameters. It's a common problem with parameterized SQL - when you want to be able to specify a variable number of values, you need to vary the SQL. There may be a MySQL-specific way of coping with this (like table-valued parameters in SQL Server 2008) but I don't believe there's a generic JDBC way of doing this.

Categories

Resources