How to order queries in sql in flutter? - sql

I am using sqlite database in Flutter. with provide and sqlite libraries. I want to get ordered list of String in the database when I get the list from sqlite. How can I achieve this? Thank you for your response!

You can use orderBy variable inside query method like this:
Future<List<SingleShiftModel>> getShiftModelsForParticularGroup(
String groupId) async {
Database db = await database;
final List<Map<String, dynamic>> maps = await db.query(
allShiftsTableName,
where: 'parentId = ?',
orderBy: "date ASC", // here you can add your custom order exactly like sqlite but EXCLUDE `ORDER BY`.
whereArgs: [groupId],
);
return List.generate(
maps.length,
(i) => SingleShiftModel.toShiftModelObject(maps[i]),
);
}

Related

How to 'replace' table name in raw SQL query?

I have the following SQL query, which works:
await sequelize.query(
"DELETE FROM `table_name` WHERE (?) IN (?)",
{
replacements: ["project_id", projectIds],
type: QueryTypes.DELETE,
}
);
But I also want to use a replacement for table_name like this:
await sequelize.query(
"DELETE FROM (?) WHERE (?) IN (?)",
{
replacements: ["table_name", "project_id", projectIds],
type: QueryTypes.DELETE,
}
);
But this doesn't work and generates an error about SQL syntax. How can I make this work?
You are mixing data value binding and quoting identifiers.
There is ancient issue in the repo: https://github.com/sequelize/sequelize/issues/4494, which sounds like the problem above.
I believe you can create a workaround that respects different sql dialects like this:
const queryInterface = sequelize.getQueryInterface();
const tableName = queryInterface.quoteIdentifier("projects");
const columnName = queryInterface.quoteIdentifier("project_id");
await sequelize.query(`DELETE FROM ${tableName} WHERE ${columnName} IN (?)`, {
replacements: [project_ids],
type: QueryTypes.DELETE,
});
Assuming you are using sequelize 6.x.

NODE JS Passing characters in get request

I am using Node and Express with MSNODESQLV8 to write an API demo (my first) to get some rows from a remote SQL Server instance. My other get queries work fine when searching for an ID which is a number but I am unsure how to pass a value in the form of characters to a parameter in my query. Pretty sure req.params.id is not appropriate.
app.get("/productsname/:id", (req, res) => {
const productName = req.params.id;
const productsNameQuery = "SELECT * FROM Products WHERE ProductName = ?";
sql.query(connStr, productsNameQuery, [productName], (err, rows) => {
if (err) {
console.log(`Failed to get product by id ${req.params.id}. ${err}`);
res.sendStatus(500);
}else {
res.json(rows);
}
})
});
I want to take a product name (string?) in at the end of the url where it reads "id" and pass it as a value to the productName const. The end goal is to retrieve all rows from the SQL table where the product name is "processor" in the get url (http://localhost:2000/productname/proccesor). Perhaps I am passing the url incorrectly?
Apologies if this is really basic. I am very new to this.
Thanks in advance

Simple select with max using scalike jdbc

Still trying to get familiar with scalikejdbc. What is the simplest way to just use sql syntax to send a query using scalike jdbc into a table to get max date? Something really simple like the below works fine but gives me an error when I try to add max around the column.
val maxDate: Option[String] = DB readOnly { implicit session =>
sql"select <column> from <table>"
.map(rs => rs.string("<column")).first.apply()
}
this does not work:
val maxDate: Option[String] = DB readOnly { implicit session =>
sql"select max(<column>) from <table>"
.map(rs => rs.string("<column")).first.apply()
}
error:
Failed to retrieve value because The column name not found.. If you're using SQLInterpolation,...
I expect this happens because column max(MyColumn) does not have name "MyColumn" by default. You may try something like this instead
val maxDate: Option[String] = DB readOnly { implicit session =>
sql"select max(MyColumn) as MyColumn_max from MyTable"
.map(rs => rs.string("MyColumn_max")).first.apply()
}

Retrieving Data in Webmatrix without 'foreach'

I want to retrieve a single item of data from my database to then use as a value for an input element.
Using the below will retrieve each instance of SubmittedBy in the DB so results in multiple results.
var UserId = WebSecurity.CurrentUserId;
var db = Database.Open("testDB");
var selectQueryString = "Select SubmittedBy FROM Posts WHERE UserId=#0";
var data = db.Query(selectQueryString, UserId);
#foreach(var row in data)
{
<input type="email" name="emailfrom" id="emailfrom" value="#SubmittedBy"/>
}
How do I retrieve SubmittedBy so it only gives the one result i.e. without the foreach loop?
Thanks in advance!!!
If by your data restriccions are you going to obtain 1 and only 1 value for an specific UserId, you could use
var SubmyttedValue = db.QueryValue(selectQueryString, UserId);
There is a method created specifically for this purpose called QuerySingle - just change your query like this:
var data = db.QuerySingle(selectQueryString, UserId);
I hope this helps!
Change your query like this:
Select SubmittedBy FROM Posts WHERE UserId=#0 LIMIT 1

MySQL: Query Cacheing (How do I use memcache?)

I have an query like:
SELECT id as OfferId FROM offers
WHERE concat(partycode, connectioncode) = ?
AND CURDATE() BETWEEN offer_start_date
AND offer_end_date AND id IN ("121211, 123341,151512,5145626 ");
Now I want to cache the results of this query using memcache and so my question is
How can I cache an query using memcache.
I am currently using CURDATE() which cannot be used if we want to implement caching and so how can I get current date functionality without using CURDATE() function ?
Something like this should work:
function getOffers($ids) {
$key = implode(',', $ids);
$cache = new Memcache();
$cache->connect('localhost');
$content = $cache->get($key);
if ($content === false) {
// content is not cached, so we have to run the query
$content = $yourDb->query('your query here');
$cache->add($key, $content);
}
$cache->close();
return $content;
}
getOffers(array('121211','123341','151512','5145626'));
You can take this a step further by sorting $ids so that the same "set" of IDs (but in a different order) will still take advantage of an available cache for that set.
This isn't date-sensitive, but you can make it date sensitive by adding the date string to $key