How do we use a LIKE with wildcards in a custom sql with servicestack ORMLite?
Following code does not seem to work:
var sql="SELECT TOP 10 Id,Value FROM SomeTable WHERE Value Like '%#term%'"
var results = Db.Select<CustomDTO>(sql, new {term = "stringToSearch"})
You need to add the wildcard to the param value, e.g:
var sql = "SELECT Id,Value FROM SomeTable WHERE Value Like #term";
var results = db.Select<SomeTable>(sql, new { term = "%foo%" });
You can run this Live Example on Gistlyn to test it.
Related
I try to create a query in the shard project in xamarin.
I can successfully create a connection to my local DB with dependecy services. But I'm not able to create a query.
Here is my code:
Connection to DB(successfully)
SQLite.SQLiteConnection DBConnection = DependencyService.Get<IDBHelper>().DbConnection(DBPath);
Get table Info (successfully)
var TableInfo = DBConnection.GetTableInfo("SomeTableName");
Query (failed)
var ReturnValue = DBConnection.Query<string>("Select * from SomeTable Where SomeColumn Like 'Value'");
Viusal Studio shows me the problem, its the <string> part. But I have no idea what I have to change.
How can I create a simple select query?
You are probably using the SQLite-Net package. This works like an ORM over SQLite database.
The generic part (where you did put <string>) is the type of object that the query must expect when getting results.
It will automatically turn the resultset into a list of your queried type.
As you are querying all data from the SomeTable table each row will represent a SomeTable object (I guess you have created such class).
Just change this line to:
var ReturnValue = DBConnection.Query<SomeTable>("Select * from SomeTable Where SomeColumn Like 'Value'");
or
var ReturnValue = DBConnection.Query<object>("Select * from SomeTable Where SomeColumn Like 'Value'");
You can get a step by step using SQLite at the official sqlite-net documentation.
I hope it helps.
First of all, I'm using ASP.NET and whenever I execute the query on SQL Server it works just fine but when I execute it from ASP.NET it returns 0 rows - how is that even possible?
Here is my code:
asp.net :
List<string> tmp = new List<string>();
string value = "hello"
sql = "select a.id AID from article a where a.TheArticle like (N'%finder.aspx?hashtag=#data%')";
using (var sqlc = new SqlCommand(sql, con))
{
sqlc.Parameters.AddWithValue("#data",value);
using (var reader = sqlc.ExecuteReader())
{
while (reader.Read())
{
tmp.Add(reader["AID"].ToString().Trim());
}
}
}
and here is the query on SQL Server:
select a.id
from article a
where a.TheArticle like (N'%finder.aspx?hashtag=hello%')
So this is begin to annoying me. What I think is parameter.addwithvalue instruction makes the SQL string just like this:
select a.id AID
from article a
where a.TheArticle like (N'%finder.aspx?hashtag='hello'%
I don't really know what has just happened so please someone explain it to me.
Please: I want to prevent SQL Injection as well
try this:
firstly modify the sql command as follow:
sql = "select a.id AID from article a where a.TheArticle like (N'%finder.aspx?hashtag=#data')"
then:
sqlc.Parameters.AddWithValue("#data", string.Concat(value, "%"));
I have a form built in webmatrix that will be updating data within a user specified database.
I would like the user to insert their DB name into the form, and have the Database.Open("SQLServerConnectionString"); open based on the users submission.
if not possible, is there a way to simply include the user specified DB name within the SQL query below within webmatrix? Sample of what I have below:
var db = Database.Open("SQLServerConnectionString");
var selectQueryString = "SELECT donor_id,first_name,last_name FROM SUPPORT.dpo.dp WHERE donor_id=#0";
I would like the static "SUPPORT" database in the FROM clause to be updated dynamically based on user input. Any help would be great.
Are you using .mdf files or actual database connection strings? If connection strings you can use the OpenConnectionString method and pass a custom connection string instead of using whats in the web.config.
http://msdn.microsoft.com/en-us/library/gg569301(v=VS.99).aspx
Something like this would probably work:
#{
var databaseName = Request["databaseName"]; //load from request
var connectionString = string.Format("Data Source=.\\SQLExpress;Initial Catalog={0};Integrated Security=True", databaseName);
var providerName = "System.Data.SqlClient";
var db = Database.OpenConnectionString(connectionString, providerName);
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}
You can just drop the SUPPORT. prefix as its not necessary for the select statement.
i'm trying to figure out how I can use Linq to filter out some of my appsettings from my web.config file.
i'm trying to do something like the following (which has wrong syntax) :-
var query = from q in System.Web.Configuration.WebConfigurationManager.AppSettings.Keys
where q.StartsWith("Foo")
select q);
what have I done wrong?
edit: added screenie (here's a link to it)
alt text http://img21.imageshack.us/img21/5516/errorji.png
Try this if you want the values:
var settings = System.Web.Configuration.WebConfigurationManager.AppSettings;
var query = from string q in settings.Keys
where q.StartsWith("Foo")
select settings[q];
Could be because KeysCollection only implements IEnumerable not IEnumerable<T>. Try using the Cast method on the Keys property first, something like:
var query = from q in System.Web.Configuration.WebConfigurationManager.AppSettings.Keys.Cast<string>()
where q.StartsWith("Foo")
select q;
I was able to think of the following
var appStngVals = from s in ConfigurationManager.AppSettings.OfType<string>()
where s.StartsWith("Foo")
select ConfigurationManager.AppSettings[s];
(as applicable to a console app)
I'm developing an application in AIR via Flex, but I'm not seeing where I'm going wrong with SQLite (I'm used to MySQL). Parameters work, but only in certain instances. Is this part of the built-in sanitation system against sql injection? Thanks for any help!
Works:
sqlite
"INSERT :Fields FROM Category", where the parameter is :Fields = "*"
as3
var statement:SQLStatement = new SQLStatement();
statement.connection = connection;
statement.text = "INSERT :Fields FROM Category";
statement.parameters[":Fields"] = "*";
statement.execute;
Doesn't Work (SQL syntax error at ":Table"):
sqlite
"INSERT :Fields FROM :Table", where the parameters are :Fields = "*" and :Table = "Category"
as3
var statement:SQLStatement = new SQLStatement();
statement.connection = connection;
statement.text = "INSERT :Fields FROM :Table";
statement.parameters[":Fields"] = "*";
statement.parameters[":Table"] = "Category";
statement.execute;
Generally one cannot use SQL parameters/placeholders for database identifiers (tables, columns, views, schemas, etc.) or database functions (e.g., CURRENT_DATE), but instead only for binding literal values.
With server-side support for parameterized (a.k.a. prepared) statements, the DB engine parses your query once, remembering out the peculiars of any parameters -- their types, max lengths, precisions, etc. -- that you will bind in subsequent executions of the already-parsed query. But the query cannot be properly parsed into its syntactic elements if critical bits, like database objects, are unknown.
So, one generally has to substitute table names oneself, in a stored procedure or in client code which dynamically concats/interpolates/whatevers the SQL statement to be properly executed. In any case, please remember to use your SQL API's function for quoting database identifiers, since the API won't do it for you.
Not sure if this is the same but I ran across something similar in Java. Basically you can't add a table as a parameter so you must generate the statement like so:
var statement:SQLStatement = new SQLStatement();
statement.connection = connection;
statement.text = stringUtil.substitute("INSERT :Fields FROM {0}", "Category");
statement.parameters[":Fields"] = "*";
statement.execute;
This is mostly likely not the securest solution, so you might want to some custom validation of the data before you add the table name.. so someone doesn't try to send it the table name ";drop tableName..."