Last four items of the websql database - html

This is my function for all the data from my database. I only want the last four data out of the database.
function spelerWeergeven()
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM speler', [], function (tx, results)
{
var len = results.rows.length, i;
if(len > 0)
{
$('#spelerTabel').replaceWith('<table id="spelerTabel"><tr><th>Spelers</th></tr></table>');
$('#spelerTabel').hide();
for(var i = 0; i< len; i++)
{
$('#spelerTabel tr:last').after('<tr><td>'+results.rows.item(i).naam+'</td></tr>');
}
$('#spelerTabel').show('slow');
}
}, null);
}
);
}
Does anybody know the answer?

SELECT * FROM `speler` ORDER BY `id` DESC LIMIT 4;

This should work
SELECT *
FROM `speler`
ORDER BY `id` DESC
LIMIT 4;
(The backticks (`) are used to prevent SQL from reading the words between them as a keyword. It's a good thing to keep that in mind, since there are many, many keywords in SQL.)
Edit:
Since you have created a table called speler with the columns id (which is the primary key) and naam using the query CREATE TABLE IF NOT EXISTS speler (id INTEGER PRIMARY KEY, naam), we know your primary key column is id.
PS: It's a good thing to let table names start with capital letter (Speler), by convention.

This will do it server side:
SELECT TOP 4 * FROM
speler
ORDER BY id DESC
Also pretty clean using Linq:
//dc would be a linq datacontext
string cmd = #"SELECT TOP 4 * from speler order by id DESC";
IEnumerable<speler> fourItems = dc.ExecuteQuery<speler>(cmd);

Related

Sql Query to fetch fare price from csv database

i have database in csv format, and i want to calculate fare from one station to another station but problem is database, i think is not in proper format to build SQL query, so can we try sql query from below database format to fetch fare price from versova to sakinaka as an example.
also is there any other solution table structure which will be friendly for firing sql queries on it.
Load your CSV into a System.Data.DataTable (C#).
Create Table T_Hop
HOP_Id integer not NULL
,HOP_Name nvarchar(200)
Create Table T_Fare
Fare_Id integer not null
,Fare_Departure_HOP_Id integer not null
,Fare_Destination_HOP_Id integer not null
,Fare_Fare numeric(10, 2) not null
take first row
foreach column ==> add hop name with id = ordinal index of column
for(int i=0; i < dt.Columns.Count; ++i)
{
for(int j=0; j < dt.Rows.Count; ++j)
{
double Fare = System.Convert.ToDouble(dt.Rows[j][i]);
==> insert into T_Fare(Fare_Id,Fare_Departure_HOP_Id, Fare_Destination_HOP_Id, Fare_Fare ) Values (j*dt.Columns.Count + i, i, j, Fare)
// and check that I didn't mix up i and j
}
}
Query:
SELECT Fare_Fare
WHERE Fare_Destionation_HopId = x
and Fare_Departure_Hop_Id = y

how to optimize a long query mysql

How to optimze this query mysql :
SELECT * FROM rooms WHERE caption LIKE #query OR owner LIKE #query AND roomtype = 'private' ORDER BY users_now DESC LIMIT 50
This is my code:
internal ServerMessage SerializeSearchResults(string SearchQuery)
{
DataTable Data = new DataTable();
using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().getQueryreactor())
{
if (SearchQuery.Length > 0)
{
if (SearchQuery.ToLower().StartsWith("owner:"))
{
dbClient.setQuery("SELECT * FROM rooms WHERE owner = #query AND roomtype = 'private' ORDER BY users_now DESC LIMIT 50");
dbClient.addParameter("query", SearchQuery.Remove(0, 6));
}
else
{
dbClient.setQuery("SELECT * FROM rooms WHERE caption LIKE #query OR owner LIKE #query AND roomtype = 'private' ORDER BY users_now DESC LIMIT 50");
dbClient.addParameter("query", "%" + SearchQuery + "%");
}
Data = dbClient.getTable();
}
}
List<RoomData> Results = new List<RoomData>();
if (Data != null)
{
foreach (DataRow Row in Data.Rows)
{
RoomData RData = PlusEnvironment.GetGame().GetRoomManager().FetchRoomData(Convert.ToUInt32(Row["id"]), Row);
Results.Add(RData);
}
}
The best way to optimize the performance of the query is to add indexes to the fields that you are using more frequently in your where clauses. For example, in MySQL you can add an index like this:
ALTER TABLE `rooms` ADD INDEX `owner` (`owner`)
The query doesn't look particularly complicate so you might try adding an index by roomtype and users_now to speed up SELECT.
CREATE INDEX index_name ON rooms (roomtype ASC, users_now DESC)
Also try to limit the usage of LIKE in a query as it severely affects performance.

How to do a count(*) in Hibernate?

How can I count the records in a MySQL table in Hibernate? I tried the following HQL, but it does not work.
SELECT COUNT(*) FROM MEMBERS WHERE `username` =:USERNAME OR `email` =:EMAIL
It is used in the following method:
public boolean checkInfos() {
Session newSession = NewHibernateUtil.getSessionFactory().openSession();
int count = (Integer) newSession.createSQLQuery("SELECT COUNT(*) FROM MEMBERS WHERE `username` ='admin' OR `email` ='admin'").uniqueResult();
if (count >= 1) {
return false;
} else {
return true;
}
}
I guess you need that
Query q = newSession.createSQLQuery("SELECT COUNT(*) FROM MEMBERS WHERE username = ? OR email =?");
q.setParameter( 1, "your username");
q.setParameter(2, "your email");
Select count(*) returns a Long, not an Integer.
One more thing: The backticks, which you are using, are not accepted by every database.
By the way, you can use count(*) also in HQL. This means, you can use createQuery instead of createSQLQuery. An advantage of HQL is, it is portable from one database to another, which is not always the case for SQL statements.
You also can achieve this by using criteria also.
private Number getCount(){
Criteria criteria = session.createCriteria(Members.class);
criteria.add(Restrictions.or(Restrictions.eq("username", "admin"), Restrictions.eq("email","admin")));
criteria.setProjection(Projections.rowCount());
return (Number) criteria.list();
}

mysql_fetch_row and ORDER BY - what am I doing wrong?

Sorry for the vague title, but I've been trying to nail this for a week and have run out of ideas.
Table: name: scores
id name password intuition
(int, varchar, varchar, int)
(5 rows with made-up values)
The PHP:
$userResult = mysql_query("SELECT `intuition` FROM `scores` ORDER BY `intuition` DESC LIMIT 4,1");
if($userResult ==NULL)
{ die(mysql_error());
}else
{ if($userResult ==FALSE)
{ die("ranking query failed, sorry");
}else
{ if(mysql_num_rows($userResult) ==NULL)
{ die("No ranking results found.");
}else
{ $queryRow = mysql_fetch_row($userResult);
$topIntuition = $query_row['intuition'];
die("queryRow =$queryRow; topIntuition =$topIntuition");
}
}
}
Output:
query row =Array; topIntuition =
where topIntuition should be the fifth highest result, currently the integer 2. What am I doing wrong?
EDIT: $query_row[<name of row>] does not work, but $query_row[0] does.
LIMIT 4, 1 will return the fifth highest result (as LIMIT 0, 1 returns the first).
Regardless, mysql_fetch_row returns an array with keys that are numeric - try $queryRow[0];
Alternatively, you can switch to mysql_fetch_array or mysql_fetch_assoc.

How to read and insert back in the database using linq to sql?

I read a set of data from database first
Insert a new record using same data in same table.
I tried this but:-
using (var db = new
DataContext(ConfigurationManager.ConnectionStrings["DB"].ToString()))
{
var items = from t in db.Table1
where t.ID.Equals(100)
select t;
foreach (var item in items)
{
using (var db1 = new
DataContext(ConfigurationManager.ConnectionStrings["DB"].ToString()))
{
Table1 tab = new Table1
{
FName = item.FName,
LName = item.LName,
Number = item.Number,
};
db1.Table1.InsertAllOnSubmit(tab);
db1.SubmitChanges();
}
}
}
I can't compile it. It throws this error at line 'db1.Table1.InsertAllOnSubmit(tab)':-
'System.Data.Linq.Table.InsertAllOnSubmit(System.Collections.Generic.IEnumerable)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly.
Your code has some flaws.
You seem to read one Table1 (assuming the id is unique) but you are treating it like a collection
Quick try since you anyway add only one table1 at a time: Replace
db1.Table1.InsertAllOnSubmit(tab);
by
db1.Table1.InsertOnSubmit(tab);
If your ID is not unique try:
List<Table1> items = (from t in db.Table1
where t.ID.Equals(100)
select t).ToList();
The rest of the code can stay the same (but still replace the InsertAllOnSubmit)
Update
You can simplify bigtime:
using (var db = new
DataContext(ConfigurationManager.ConnectionStrings["DB"].ToString()))
{
Table1 thisTable = (from t in db.Table1
where t.ID. == 100
select t).SingleOrDefault();
if ( thisTable != null)
{
Table1 tab = new Table1 ()
{
FName = item.FName,
LName = item.LName,
Number = item.Number, };
db.Table1.InsertOnsubmit(tab)
db.SubmitChanges();
}
}
}
if you are 100% sure your id will always match use .Single() instead of .SingleOrDefault(). Single will throw an exception if no result matches. SingleOrDefault returns NULL in this case.