Add '%' to string for SQL search - c#

At the moment i have a textbox and a button and i can read the textbox fine and it searches the databse for say "apple"
but if there is a result called "red apple" it will not return it.
I have tried
string getTheBox = (this.searchBox.Text);
string request = "%" + getTheBox + "%";
But it doesn't seem to be working. This is with "request" being the string variable.
EDIT to include the SQL request part
SqlDataSource2.SelectCommand = "SELECT Recipe_Name FROM New_Recipe WHERE [ingredient1]=#request
SqlDataSource2.SelectParameters.Add(newParameter("request",System.TypeCode.String));
SqlDataSource2.SelectParameters["request"].DefaultValue = request;

The adding of % is correct, but you need to change your sql query
you need to use the LIKE operator
for example THE QUERY could be
"SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #request"
and your code
string request = "%" + getTheBox + "%";
string sqlText = "SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #request";
using(SqlConnection cn = GetSqlConnection())
{
cn.Open();
using(SqlCommand cmd = new SqlCommand(sqlText, cm);
{
cmd.Parameters.AddWithValue("#request", request);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
......
}
}
}

Please post your SQL query too. Perhaps you need to change WHERE FruitName = #FruitName to WHERE FruitName LIKE #FruitName

This is a horrible idea, as anyone can run sql injection. You probably want something akin to
Sqlcommand.Prepare
As it will let you set safer arguements. And have two words.

I usually have a few helper functions to add like to my queries depending on what I need done.
public List<T> GetRecipesThatContain<T>(string ingredient)
{
const string commandText = "SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #SearchTerm";
var searchTerm = Contains(ingredient);
using(var connection = GetSqlConnection())
{
connection.Open();
using(var command = new SqlCommand(commandText, connection);
{
command.Parameters.AddWithValue("#SearchTerm", searchTerm);
using(var reader = command.ExecuteReader())
{
var results = new List<T>();
while(reader.Read())
{
// Get results
// results.Add(result);
}
return results;
}
}
}
}
private string StartsWith(string searchTerm)
{
return string.Format("{0}%", searchTerm);
}
private string EndsWith(string searchTerm)
{
return string.Format("%{0}", searchTerm);
}
private string Contains(string searchTerm)
{
return string.Format("%{0}%", searchTerm);
}

Related

Query to the database having a field in string

Can I somehow query the database for a field that I have in string?
string fieldName = "Column1";
SQL:
string sql = "SELECT " + fieldName + " FROM myTable";
I need to do this using LINQ
Is there something built-in and quick for such questions or does reflection come into play?
You can implement a simple method for this:
private static IEnumerable<IDataRecord> ReadSqlRecords(string sql) {
//TODO: Put connection string here
//TODO: I've assumed you work with MS SQL; if not replace SqlConnection
using (var conn = new SqlConnection("ConnectionStringHere")) {
conn.Open();
using (var q = conn.CreateCommand()) {
q.CommandText = sql;
using (var reader = q.ExecuteReader()) {
while (reader.Read())
yield return reader;
}
}
}
}
Then you can use it
string sql = $"SELECT {fieldName} FROM myTable";
// Now you can put Linq
var result = ReadSqlRecords(sql)
.Where(record => Convert.ToInt32(record["Id"]) > 100)
.Count();
Try this:
using (var context = new MyContext())
{
// Get the object from the table (in this case I give an example to get the first row. You can use Where for the condition)
var row = context.MyTable.FirstOrDefault();
// Get the field value with reflection
response = row.GetType().GetProperty(name).GetValue(row, null).ToString();
}

How to solve The name "connectionclass" does not exist in the current context?

So, I want to make a drop down list. I have the connectionclass.cs, which connects the database to an array list. But when I build the dropdown list, doesn't find the connectionclass
Sorry, i am a bit tired. So, this is the classconnection.cs.
There is the ss
namespace YourCoffeeShop.App_Code
{
public static class ConnectionClass
{
private static SqlConnection conn;
private static SqlCommand command;
static ConnectionClass()
{
string connectionString = ConfigurationManager.ConnectionStrings["cafeaconnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
}
public static ArrayList GetCafeaByType(string cafeaType)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM tipuridecafea WHERE tip LIKE '{0}'", cafeaType);
try
{
conn.Open();
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
int id = reader.GetInt32(0);
string nume = reader.GetString(1);
string tip = reader.GetString(2);
double pret = reader.GetDouble(3);
string roast = reader.GetString(4);
string tara = reader.GetString(5);
string imagine = reader.GetString(6);
string review = reader.GetString(7);
cafeacs tipuridecafea = new cafeacs(id, nume, tip, pret, roast, tara, imagine, review);
list.Add(tipuridecafea);
}
}
finally
{
conn.Close();
}
return list;
}
You did not post your entire class, but the answer is that C# is case-sensitive, so:
ArrayList shirtList = connectionclass.GetShirtByType(DropDownList1.SelectedValue);
is not equivalent to:
ArrayList shirtList = ConnectionClass.GetShirtByType(DropDownList1.SelectedValue);
Provided that the .GetShirtByType(...) method exists in the class and is static, the second example above would correct your error.
I discovered what the problem was. I went into ConnectionClass.cs properties and changed the build action to compile and then added the using YourCoffeeShop.App_Code. It works now, thanks everyone!

Input string was not in a correct format error not getting resolved for class function

I am getting the error as
Input string was not in a correct format.
newRow["col_frm_bin_id"] = CF.ExecuteScaler("Select location_name from wms_storage_bin where mkey = " + e.Record["from_bin"] + "");
public string ExecuteScaler(string StrQuery)
{
DB.EConnection();
cmd = new SqlCommand(StrQuery, DB.conn);
cmd.Connection = DB.conn;
int val=Convert.ToInt32(cmd.ExecuteScalar());
DB.conn.Close();
string ret = val.ToString();
return ret;
}
I tried with converting but still it didn't worked
Your return column name sounds like its a string variable, Change it with int type column, or remove Convert.ToInt32 from code side
public string ExecuteScaler(string StrQuery)
{
DB.EConnection();
cmd = new SqlCommand(StrQuery, DB.conn);
cmd.Connection = DB.conn;
string ret=cmd.ExecuteScalar().ToString();
DB.conn.Close();
return ret;
}
i think you should do like this but this is not good practice and also not safe
your mkey value should be in between quotes
mkey = '" + e.Record["from_bin"] + "'
newRow["col_frm_bin_id"] = CF.ExecuteScaler("Select location_name from wms_storage_bin where mkey = '" + e.Record["from_bin"] + "'");
public string ExecuteScaler(string StrQuery)
{
DB.EConnection();
cmd = new SqlCommand(StrQuery, DB.conn);
cmd.Connection = DB.conn;
int val=Convert.ToInt32(cmd.ExecuteScalar());
DB.conn.Close();
string ret = val.ToString();
return ret;
}
but sending parameters is best practice
I'll try summarize various pieces of information from other answers and comments.
First, your existing code is open to Sql injections. This is a very bad thing. To avoid the risk of Sql injection you shoul use Parametrized queries. See for instance here.
That means your ExecuteScaler method should not take a string as its argument, but instead a SqlCommand (I have corrected the spelling of scalar):
public string ExecuteScalar(SqlCommand query) { ... }
Your current implementation of ExecuteScaler is also at risk of leaking SqlConnetions. If an exception is thrown in this method before the DB.conn.Close() line, the connection will not be closed. For instance, in the case you described in the question, the following line is the prime suspect:
int val = Convert.ToInt32(cmd.ExecuteScalar());
With your current call to the method, you seem to be fetching something that is a string from the database. Unless that string is convertible to Int32, this line will throw an exception, and the connection will not be closed. To fix this, you should at the minimum add a try { ... } finally { ... } block:
public string ExecuteScalar(SqlCommand query)
{
try
{
DB.EConnection();
query.Connection = DB.conn;
string ret = query.ExecuteScalar().ToString();
return ret;
}
finally
{
if(DB.conn.State == ConnectionState.Open)
DB.conn.Close();
}
}
I would also suggest that you create separate versions of ExecuteScalar for different expected return types. Perhaps:
public string GetStringScalar(SqlCommand query)
public int GetInt32Scalar(SqlCommand query)
etc.
The calling code then needs to be changed:
string locName = null;
using (SqlCommand locNameCommand = new SqlCommand(#"
select location_name
from wms_storage_bin
where mkey = #mkey
"))
{
locNameCommand.Parameters.AddWithValue("mkey", e.Record["from_bin"]);
locName = GetStringScalar(locNameCommand);
}
newRow["col_frm_bin_id"] = locName;

cek valid data in table with input ";" and where in

i want to check valid data...
i have a table Divisi with sample data like this:
=====================
IdDivisi NamaDivisi
=====================
1 DivisiA
2 DivisiB
3 DivisiC
in my code, i get value :
string data = DivisiA;DivXXX
so, when checked, the alert will appear invalid data.
I want to get a query like this:
select NamaDivisi from Divisi where NamaDivisi IN('DivisiA','DivXXX')
and the result is null or empty or invalid.
because there are values ​​/ data 'DivXXX' is not valid on the table Divisi
But this time, when I debug, I get the query result like this:
select NamaDivisi from Divisi where NamaDivisi IN ('DivisiA;DivXXX')
===================================================
This is the full code.
private string CekValidDivisi(string data)
{
DivisiFacade div = new DivisiFacade();
string getDivisi = div.CekValidData(data);
return getDivisi;
}
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + data + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
please help me to resolve the problem in my code. thank you ...
You have multiple problems in your code, but this is not a place to teach you basics, so I'll try to stick to the topic. If you want to have a parameter like that, you have to create it like that first. I guess the data contains string with value DivisiA;DivXXX (and I presume DivXXX is just a generic name meaning you have multiple divisions there). Probably the easiest way would be to do something like this with it
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string paramData = ParseData(data);
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + paramData + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
private string ParseData(string data)
{
return data.Replace(";", "','");
}
Haven't tried it, but hope you get the idea. Either way, please for your own sake, do some research on what is the best way to handle sql connections in c# and also how to prevent SQL injections.

C# / Sqlite simple way to store query result as variable

I am semi-new to C# but in particular using Sqlite within C#, currently I have a SQlite DB setup fine in terms of it connects with the application well I am running windows form application and I have bound a table within the database to a datagrid view.
This is all fine I have a function setup to run queries where i pass the SQL statement as a string to the function and it runs it as a query.
I was wandering how I do I get a result back from the query I know obviosuly it will be somthing like
private string QueryResult(string query){
connect
run query
read query
return result
}
All th examples I have seen use Sqlreader but I can't seem to get it work, I am really used to using PHP with SQL and that seems so much simpler than using it in C# can someone explain or point out somewhere I might be able to find a tutuorial or function that you can run any query in by passing it as a string and getting the result returned pretty simply? The results I need wont be arrays or huge things I am only looking to return 1 word strings or numbers at a time so I don't need anything complicated.
Please help me out I spent about 4 hours reading about this stuff last night and didn't seem to get anywhere.
Try this, maybe it will help you:
public string QueryResult(string query)
{
string result = "";
SQLiteConnection sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
try
{
sqlite.Open(); //Initiate connection to the db
SQLiteCommand cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
result = cmd.ExecuteScalar().ToString();
}
finally
{
sqlite.Close();
}
return result;
}
Heres a method that I have Used....
First off, build a class to represent a Table in your DataBase :-
public class Contact
{
public int ContactID { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public string MobileNumber { get; set; }
public string EmailAddress { get; set; }
public string Information { get; set; }
}
Then I load this Data into an IEnumerable List :-
public List<Contact> GetContacts()
{
DataTable dt = new DataTable();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Contacts]", Connection);
Adapter.SelectCommand = cmd;
Connection.Open();
Adapter.SelectCommand.ExecuteNonQuery();
Adapter.Fill(dt);
Connection.Close();
var Contacts = (from row in dt.AsEnumerable()
select new Contact
{
ContactID = row.Field<int>("ContactID"),
Surname = row.Field<string>("Surname"),
Forename = row.Field<string>("Forename"),
MobileNumber = row.Field<string>("MobileNumber"),
EmailAddress = row.Field<string>("EmailAddress"),
Information = row.Field<string>("Information")
}).ToList();
return Contacts;
}
In My application I create an Instance of this Object :-
public List<Contact> contactData;
contactData = dc.GetContacts();
I now have the power to manipulate the data using LINQ :-
var Query = ConactData.Where(item=> item.ContactID == 10)
.Select(item=> item.Surname).toString();
You can use LINQ to query your Data and store it as Lists, Strings etc etc.
Hope This Helps.
Usually, I do something like:
string CONNECTION_STRING = "Persist Security Info=False; Integrated Security = SSPI; Initial Catalog=DATABASENAME;Data Source=SERVERIP";
string query = "IF OBJECT_ID('TABLE_NAME') IS NOT NULL SELECT * FROM TABLE_NAME";
using (SqlConnection Connection = new SqlConnection(CONNECTION_STRING))
{
using (SqlCommand sqlCommand = new SqlCommand(query, ConnectionString))
{
try
{
Connection.Open();
SqlDataReader queryCommandReader = sqlCommand.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(queryCommandReader);
if (dataTable != null)
{
if (dataTable.Rows != null)
{
if (dataTable.Rows.Count > 0)
{
String rowText = "";
rowText += dataTable.Rows[ROW_NUM] [COLUMN_NAME];
}
}
}
}
catch (Exception)
{
...
}
finally
{
...
}
//in normal logic
SELECT (SELECT SUM(column_name) FROM table_name WHERE condition) - (SELECT SUM(column_name) FROM table_name WHERE condition)
//actual coding example
public void total_due()
{
string query = "select (select sum(amount) from table_name where id>0 and amount>paid and [order no] like '" + textbox1.Text + "%' and [name] like '" + textbox2.Text + "%' and [date] like '" + textbox3.Text + "%' ) - (select sum(paid) from table_name where id>0 and amount>paid and [order no] like '" + textbox1.Text + "%' and [name] like '" + textbox2.Text + "%' and [date] like '" + textbox3.Text + "%' )";
SqlConnection con = new SqlConnection("server=server_name;Database=database_name;UID=sa;Password=password;");
con.Open();
SqlCommand cmd = new SqlCommand(query,con);
due.Text = cmd.ExecuteScalar().ToString();
con.Close();
}

Categories

Resources