intersystem cache C# query with name like? - c#

I am trying to use like in a Cache sql query such as:
select * from person where name like ?.
I am passing the parameter like below.
CacheParameter param = new CachemParameter("NAME", CacheDBType.NVarChar);
param.Value = tbxName.Text.ToUpper();
command.parameters.Add(param);
Then I execute the reader.
The results is nothing.
I know in MSSQL I use name like 'Lawson%'. How do I do this in a Cache query?
TIA
Mike

According to the doc example
Your command could use %STARTSWITH instead of like:
select * from person where name %STARTSWITH ?

I finally figured out that all I had to do was to concatenate the "%" to the parameter being passed and it worked such as:
param.Value = tbxName.Text.ToUpper() + "%";

Related

Can we add parameter in datatable.select in c#

I like to know is it possible to add parameter in datatable.select(expression).For example
string query="Name=#Name";
//dt is comming from database.
dt.Select(query);
How to add this parameter #Name. I need to compare a value which contains single quote and it gets failed in the above case.
Thanks in advance
You can use String.Format, you need to escape single quotes with two:
string query = string.Format("Name='{0}'", name.Replace(#"'", "''"));
var rows = dt.Select(query);
or, if you want to use Like:
string query = string.Format("Name LIKE '%{0}%'", name.Replace(#"'", "''"));
(note that a DataTable is not vulnerable to sql-injection since it's an in-memory object)
You can pass only expression to Select method.
In case if you need to pass the parameter dynamically then you can try this.
string Exp = "Name ='" + variable + "'";
dt.select(Exp);

Parameterizing a raw Oracle SQL query in Entity Framework

I'm trying to parameterize a raw SQL query for an Oracle synonym (non-entity) in EF 4 and I am having some problems. Currently I am doing something like the code below, based on some examples that I saw:
string term="foo";
OracleParameter p = new OracleParameter("#param1", term);
object[] parameters = new object[] { p };
var model = db.Database.SqlQuery<ProjectTask>("SELECT * FROM (SELECT * FROM web_project_task_vw WHERE project_num like '%#param1%') WHERE rownum<=100", parameters).ToList();
Running this doesn't return any results. If I replace the parameter with something like
"SELECT * FROM web_project_task_vw WHERE project_num like '%"+term+"%'"
it returns the results I expect, but this is obviously a SQL injection risk.
Can anyone point me in the right direction for how parameters are supposed to work in EF 4 for an Oracle DB?
Thanks.
First, like Mohammed wrote, you need to prefix the parameter with ':', but not as you define it, just in the query.
Second, you are currently searching not for the value of the parameter but rather strings that contains the string #param1. So surround the value of the parameter with % and you should get a result.
So it should look something like this:
string term="foo";
OracleParameter p = new OracleParameter("param1", term);
object[] parameters = new object[] { p };
var model = db.Database.SqlQuery<ProjectTask>("SELECT * FROM (SELECT * FROM web_project_task_vw WHERE project_num like '%'||:param1||'%') WHERE rownum<=100", parameters).ToList();
Your p might have an incorrect parameter name; the name should be param1, not #param1. Your query is also incorrect; replace '%#param1%' with '%:param1%'.

Select statement with where clause in C#

How to write a select statement with where clause.i need to compare with a string value.
I tried this:
string get_dropdown_value = dropdown_category.SelectedItem.Value;
...but it gives me this error:
Invalid column name 'get_dropdown_value'.
You will have to show the select statement you are using. I suspect you have done something like this:
string selectStatement = "SELECT * FROM SOME_TABLE WHERE SOME_COLUMN = get_dropdown_value";
While it should be like:
string selectStatement = "SELECT * FROM SOME_TABLE WHERE SOME_COLUMN = " + get_dropdown_value;
Edit: As others mentioned, this is prone to SQL Injection. So, you might want to use SqlParamter (assuming you are using SQL).
Try this code
insted of
string get_dropdown_value = dropdown_category.SelectedItem.Value;
Put
string get_dropdown_value = dropdown_category.SelectedItem.Text;

i'm lost: what is wrong with this ado.net code?

well, the question is clear i hope, the code is this:
string sql = "delete from #tabelnaam";
SqlCommand sc = new SqlCommand();
sc.Connection = getConnection();
sc.CommandType = CommandType.Text;
sc.CommandText = sql;
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Input;
param.ParameterName = "#tabelnaam";
param.Value = tableName;
sc.Parameters.Add(param);
OpenConnection(sc);
sc.ExecuteScalar();
tableName is supplied to this function.
I get the exception:
Must declare the table variable #tabelnaam
IIRC, you cant use a substitute the table name for a parameter.
Rather build the SQL string containing the correct table name.
Make to changes
rather than using paramter use this
string sql = string.format( "delete from {0}",tableName);
make use of executenonquery intead of ExecuteScalar
sc.ExecuteNonQuery();
As mentioned by others, you can't parameterise the table name.
However, as you rightly mention in comments on other answers, using simple string manipulation potentialy introduces a SQL injection risk:
If your table name input is fro an untrusted source, such as user input, then using this:
string sql = string.format( "DELETE FROM {0}",tableName);
leaves you open to the table name "myTable; DROP DATABASE MyDb" being inserted, to give you:
DELETE FROM myDb; DROP DATABASE MyDB
The way round this is to delimit the table name doing something such as this:
string sql = string.format("DELETE FROM dbo.[{0}]", tableName);
in combination with checking that the input does not contain either '[' or ']'; you should probably check it also doesn't contain any other characters that can't be used as a table name, such as period and quotes.
I dont think you can parameterize the table name. From what I have read you can do it via Dynamic sql and calling sp_ExecuteSQL.
Your SQL is incorrect, you are deleting from a table variable yet you haven't defined that variable.
Update: as someone has pointed out, you are trying to dynamically build a query string but have inadvertantly used SQL parameters (these do not act as place holders for string literals).
More here:
Parameterise table name in .NET/SQL?
You cannot parameterise the table name, you have to inject it into the command text.
What you can and should do is protect yourself against SQL injection by delimiting the name thus:
public static string Delimit(string name) {
return "[" + name.Replace("]", "]]") + "]";
}
// Construct the command...
sc.CommandType = CommandType.Text;
sc.CommandText = "delete from " + Delimit(tableName);
sc.ExecuteNonQuery();
See here and here for more background info.

Can I get the query that was executed from the SqlDataSource?

I have a sql query for my SelectCommand on my SqlDataSource. It looks like the following:
SELECT * FROM Books WHERE BookID = #BookID
A TextBox feeds the #BookID parameter using an Asp:ControlParameter.
When I view the SelectCommand when stepping through the code, I see this:
SELECT * FROM Books WHERE BookID = #BookID
What I want to actually see is that if the person types in 3 in the TextBox, I want to see
SELECT * FROM Books WHERE BookID = 3
I can't figure out how to access the above though?
One way to view the actual query is by using SQL Profiler.
The query is never executed as
SELECT * FROM Books WHERE BookID = 3
It's actually the parameterised query with the parameter passed.
You can do a "Find/Replace" on the query with the related parameters to see what it would look like.
(This answer presumes with the SqlClient implementation.)
No, you cannot see the executed sql code. The SqlCommand class calls sp_execute (see both SqlCommand.BuildExecute methods for the exact implementation) which separates the query from the parameters. You'll need to use Sql Profiler to see the exact query executed.
You could use the provided DbCommand (from the Selecting event) to parse your CommandText and replace the parameters with their actual values. This would need some logic for escaping, and it will not be the exact query that Sql Server executes.
Public Function GenSQLCmd(ByVal InSqlCmd As String, ByVal p As Data.Common.DbParameterCollection) As String
For Each x As Data.Common.DbParameter In p
InSqlCmd = Replace(InSqlCmd, x.ParameterName, x.Value.ToString)
Next
Return InSqlCmd
End Function
I guess you won't be able to see the select statement like you wish, since the parameter is not replaced in the statement with the value 3, but sent just like you wrote it to sql server (with the parameter).
That's actually good since it will prevent one to inject some malicious sql code in your textbox, for example.
Anyway, can't you retrieve the value passed to the parameter using this:
cmd.Parameters(0).Value
where cmd is your SqlCommand?
This is the C# version of Adam's answer
public string GenSQLCmd(string InSqlCmd, System.Data.Common.DbParameterCollection p) {
foreach (System.Data.Common.DbParameter x in p) {
InSqlCmd = InSqlCmd.Replace(x.ParameterName, "'" + x.Value.ToString() + "'");
}
return InSqlCmd;
}
Usage:
string DebugQuery = GenSQLCmd(cmd.CommandText, cmd.Parameters); //cmd is a SqlCommand instance
Yes, you can view that information but you need to do a bit coding for that.
Create an extension method called ToSqlStatement
public static class SqlExtensions
{
public static string ToSqlStatement(this IDbCommand cmd)
{
var keyValue = new List<string>();
foreach (SqlParameter param in cmd.Parameters)
{
var value = param.Value == null ? "NULL" : "'" + param.Value + "'";
keyValue.Add($"{param.ParameterName}={value}");
}
return $"{(cmd.CommandType == CommandType.StoredProcedure ? "exec " : string.Empty)}{cmd.CommandText} {string.Join(", ", keyValue)}";
}
}
Add OnSelecting event handler to SqlDataSource control on your page
In you code behind
protected void sqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
MyLogger.WriteLine(e.Command.ToSqlStatement());
}

Categories