Difference between Laravel DB::insert() and DB::table()->insert() - database

I've been trying to figure out which one to use when, and if I should even use both.
Been looking at Laravel docs and they have both in there. From what I can make out of it, DB::insert() provides more "tailored" query than DB::table()->insert() does.
Would anyone be able to clarify what exactly the difference is in the two when it comes to how and when to use which?

DB::insert() for raw sql queries. Example:
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::table()->insert() for query builder. Example:
DB::table('users')->insert(
['email' => 'john#example.com', 'votes' => 0]
);
Query builder compiles conditions to raw sql query, but I am using it because it is much more convenient.

You always try to use query builder as much as possible, it prevents SQL injection.
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings
Query Builder also helps with special chars such as ', " in values. For raw statement, you need to take care of the special chars yourself.

public function addsubEmployee(Request $reqest){
Sub_employee::create([
"se_name"=> $reqest->se_name,
]);
return redirect()->route("subEmployee");
}

Related

Concat values to use as subject in SPARQL Queries (MarkLogic)

I am attempting to do a SPARQL query in MarkLogic by concating my subject, predicate and object to use as a new "subject" node. I have attempted to do so with the query below
SELECT *
WHERE {
?subject </in/relationship/with> ?object .
BIND(concat(?subject, "/in/relationship/with", ?object) AS ?relationship
?relationship </current/status> ?status
}
However, this query does not work as ?relationship now contains a string for each row resulting in the output of the query to be completely empty. Therefore, I am wondering if this can be done and whether it is possible to convert a string into a object that SPARQL can query with.
Stanislav is correct, you need to wrap the string in IRI(). Here a code snippet that runs directly in QC. Run it against an empty database to not pollute your other data:
xdmp:document-insert('/triples.xml', <triples>{
sem:triple(sem:iri("http://my/subject1"), sem:iri("/in/relationship/with"), sem:iri("http://my/subject2")),
sem:triple(sem:iri("http://my/subject1/in/relationship/with/http://my/subject2"), sem:iri("/current/status"), "My status")
}</triples>)
;
sem:sparql('
SELECT *
WHERE {
?subject </in/relationship/with> ?object.
BIND(IRI(CONCAT(?subject, "/in/relationship/with/", ?object)) AS ?relationship)
?relationship </current/status> ?status.
}
')
Whether this is a sensible approach might depend. Keep in mind that MarkLogic is particularly strong in keeping associated data together in documents, and you can embed triples, or use TDE to project triples out of them as well, allowing you to combine strength from document search, and keeping related data together, while still allowing to reason over facts with SPARQL.
HTH!

query with like clause in scalikejdbc

Can anyone please give me a example for how to use like clause in scalikejdbc with dynamic value. I used following query but it did not work
sql"select * from tables_list where lower(TABLE_NAME) like '%$tableName.toLowerCase%'"
scalikejdbc build in prevent sql injection, therefore when you type like '%$tableName.toLowerCase%', it appear as like '%'urValue'%', hence error occur.
I found a way to go ground it, which is
def search(name:String){
val searchName = s"%$name%"
DB readOnly{ implicit session =>
sql"select * from db where name like $searchName".map
...
...
}
I hope this can help you.

Where EF6 doing where clause at SQL or at client

I am trying to start using EF6 for a project. My database is already filled with millions of records.
I can't find right explanation how does EF send T-SQL to SQL Server? I am afraid that I am going to download bunch of data to user for no reason.
In code below I have found three way to get my data to List<> but I am not sure which is right way to do WHERE clause at SQL.
I do not want to fill client with millions of record and to query (filter) that data at client.
using (rgtBaza baza = new rgtBaza())
{
var t = baza.Database.SqlQuery<CJE_DOC>("select * from cje_doc where datum between #od and #do",new SqlParameter("od", this.dateTimePickerOD.Value.Date ) ,new SqlParameter("do", this.dateTimePickerOD.Value.Date)).ToList();
var t = baza.CJE_DOC.Where(s => s.DATUM.Value >= this.dateTimePickerOD.Value.Date && s.DATUM.Value <= this.dateTimePickerDO.Value.Date).ToList();
var query = from b in baza.CJE_DOC
where b.DATUM >= this.dateTimePickerOD.Value.Date && b.DATUM.Value <= this.dateTimePickerDO.Value.Date
select b;
var t = query.ToList();
this.dataGridViewCJENICI.DataSource = t;
}
In all 3 cases, the filtering will happen on the database side, the filtering (or WHERE clause) will not take place on the client side.
If you want to verify that this is true, especially for your last 2 options, add some logging so that you can see the generated SQL:
baza.Database.Log = s => Console.WriteLine(s);
In this case, since you are using EF already, choose the 2nd or 3rd options, they are both equivalent with different syntax. Pick your favorite syntax.
In all of those examples, EF6 will generate a SQL query including the where clause - it won't perform the where clause on the client.
It won't actually retrieve any data from the database until you iterate through the results, which in the examples above, is when you call .ToList().
EF6 would only run the filter on the client if you called something like:
baza.CJE_DOC.ToList().Where(x => x.Field == value)
In this instance, it would retrieve the entire table when you called ToList(), and then use a client-side Linq query to filter the results in the where clause.
Any of the 3 will run the query on the SQL Server.
EF relies on LINQ's deferred execution model to build up an expression tree. Once you take an action that causes the expression to be enumerated (e.g. calling ToList(), ToArray(), or any of the other To*() methods), it will convert the expression tree to SQL, send the query to the server, and then start returning the results.
One of the side effects of this is that when using the query or lambda syntax, expressions that EF does not understand how to convert to SQL will cause an exception.
If you absolutely need to use some code that EF can't handle, you can break your code into multiple segments -- filtering things down as far as possible via code that can be converted to SQL, using the AsEnumerable() method to "close off" the EF expression, and doing your remaining filtering or transformations using Linq to Objects.

Can I find such a intelligent function to deal with all query conditions in database

If we want to query something in database, we can use where conditions, such as select * from user where id=1;
I can define a function :
bool query(int id,string tableName)
{
database.id.equalTo(id);
}
if I want to find the user less than 18(age) years old:
bool query(int age,string tableName)
{
database.age.lessthan(age);
}
so for two conditions we have two function relative.
Can I find such a way ,that
bool query(string condition)
{
database.find(condition);
//it will deal with the condition intelligent use the required function.
}
I know database can read sql syntax. But I want to find the function that can provide developer a convenient way without writing the sql syntax, just pass the condition sentence that: age<18, id=1. And the function return the result1.When enter arg>19 the function return the result2.
I am not sure if I have mention my problem clearly. Seeking for help!
For PHP you can use Doctrine ORM. Doctrine 2 is an object-relational mapper (ORM) for PHP 5.4+ that provides transparent persistence for PHP objects.
The 'where' clause should do what you need.
http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html#high-level-api-methods
Similar QueryBuilders exist in other languages. No need to reinvent the wheel.
http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html

Simple.Data LIKE Operator in Where

How can we use LIKE operator in WHEREusing Simple.Data for SQL Server in ASP.Net C#
I need to run this SQL Query
SELECT MAX(regid) FROM reg_course WHERE(regid LIKE '%2013%')
Finally I achieved this task by aliasing the max(regid) column and querying in this fashion.
var cid=db.course_test.All()
.Select(db.course_test.regid.Max().As("maxcourseid"))
.Where(db.course_test.regid.Like(string.Concat("%",DateTime.Now.Year,"%")))
.FirstOrDefault();
Note
cid=db.course_test.All()
.Select(db.course_test.regid.Max().As("maxcourseid"))
.Where(db.course_test.regid.Like(string.Concat("%",DateTime.Now.Year,"%")))
returns the type Simple.Data.SqlQuery
Using FirstOrDefault returns Top result. If you don't want you can iterate in collection without using FirstOrDefault
Any other Better way Suggestions??

Resources