How can I make my select line in C# check if news_title is like my query string named Search?
This is what I have tried without success. It's supposed to then fill a Repeater with results that are like the query string.
// Get data from database/repository
static DataTable GetDataFromDb()
{
string searchquery = HttpContext.Current.Request.QueryString["Search"].ToString();
var con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
con.Open();
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE ([news_title] " +
"LIKE '%' + " + searchquery + " + '%') Order By news_postdate", con);
var dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
It should be '%" + searchquery + "%'. However this kind of string concatenation is open for SQL injection. Try parameterized queries instead, something like this :
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title] " +
"LIKE #Search Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search","%" + searchquery + "%");
Or:
var da = new SqlDataAdapter("SELECT * FROM [news] WHERE [news_title]" +
" like '%' + #Search+ '%' Order By news_postdate", con);
da.SelectCommand.Parameters.AddWithValue("#Search",searchquery);
Although specify the type directly and use the Value property is more better than AddWithValue. Have a look at this Can we stop using AddWithValue() already?
Related
I have a winform and a textbox which will pass the value to a prepared statement like this
searchKey = "member_chinese_name";
field_name = "member_chinese_name";
daoQuery = "SELECT * FROM member where member_chinese_name like #" + searchKey;
sqlCmd = new MySqlCommand(daoQuery, databaseConnection);
MessageBox.Show(field_name + " " + field_value1);
sqlCmd.Parameters.Add(new MySqlParameter("#"+field_name , field_value1 + "%"));
sqlCmd.CommandTimeout = 60;
sqlCmd.ExecuteNonQuery();
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
the whole query is (select * from member where member_chinese_name like 中文字%;)
the query has no result run in my winform, but i run the sql in phpmyadmin (select * from member where member_chinese_name like '中文字%') is valid
Anyone know what is the problem?
Remarks (search english is ok)
The problem might be the parameter you are sending for the search. It should be #searchKey instead of #" + searchKey; and you can also choose sqlCmd.Parameters.AddWithValue instead of sqlCmd.Parameters.Add(new MySqlParameter thus code would look like
searchKey = "member_chinese_name";
field_name = "member_chinese_name";
daoQuery = "SELECT * FROM member where member_chinese_name like #sKey";
sqlCmd = new MySqlCommand(daoQuery, databaseConnection);
MessageBox.Show(field_name + " " + field_value1);
//not sure which variable stores 中文字
sqlCmd.Parameters.AddWithValue("#sKey", field_value1+"%");
Mabuhay!
What is the most efficient or more convenient way to do this.
I have a select query and put it on a datagridview base on my filter. It has 5 columns. I want to know if Column CA from that Datagridview already exist on Table 2 which is on Column 3?
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=db;User ID=sa;Password=pw");
// DateTime dt = new DateTime();
//dt = DateTime.Now.ToString();
SqlDataAdapter sda = new SqlDataAdapter("SELECT max(PurchaseOrder.POTitle) as Description,sum(PurchaseOrderEntry.Price *PurchaseOrderEntry.QuantityOrdered) as Amount, max(PurchaseOrder.PONumber)as PONumber, " +
" max(PurchaseOrderEntry.OrderNumber) as BoxCount, max(PurchaseOrderEntry.OrderNumber) as PLC,max(PurchaseOrderEntry.OrderNumber) as Branch, max(PurchaseOrderEntry.OrderNumber) as PreparedBy, max(PurchaseOrderEntry.OrderNumber) as CheckedBy " +
" FROM PurchaseOrder LEFT OUTER JOIN" +
" PurchaseOrderEntry ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID" +
" WHERE (PurchaseOrder.Remarks like '%" + tanggapan.Text + "%') AND (PurchaseOrder.DateCreated BETWEEN '" + dateTimePicker1.Text + "' AND '" + dateTimePicker2.Text + "' and PurchaseOrder.OtherStoreID = '" + branch.Text + "') Group By PurchaseOrder.PONumber", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
This show my query filter. Any tip on how to do if PurchaseOrderEntry.OrderNumber already exist on my records so I can manage which one repeats.
Thank you!
Chris
I added this code now on my works and it is working now.
DataTable dt = new DataTable();
dt.Clear();
dt.Reset();
con.Close();
adaptors1.SelectCommand = con.CreateCommand();
adaptors1.SelectCommand.CommandText = "Select TOP 1 [ponumber],[clref] from [ISSPandayan].[dbo].[" + branch.Text + "] where [ponumber] = '" + dr.Cells["ponumber"].Value + "' ORDER BY [clref] ASC";
adaptors1.Fill(dt);
// select query para malam kung existing ponumber
if (dt.Rows.Count == 1)
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = dt.Rows[0][1].ToString();
}
else
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = " ";
}
//adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = "";
//MessageBox.Show(Convert.ToString(dr.Cells["description"].Value));
con.Close();
con.Open();
adaptorss.InsertCommand.ExecuteNonQuery();
adaptorss.InsertCommand.Parameters.Clear();
Good day I am working on an ASP.NET C# application that searches a sql table and brings back the results in a gridview. I got it to work using the like operator but I realise that if I search a character it brings back any record with that character in it, what I want is if I search with a character I want all records starting with that character. It should also allow me to search normally, Here is what I did previously
//I have a connection manager class in my app code folder
SqlConnection connection = connectionManager.GetConnection();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = connection;
String str = "select PR_NAME_GN, PR_NAME_SURN, EVENT_PARISH, EVENT_YEAR, EVENT_TYPE, FS_IMAGE_ID from Jam01 where (PR_NAME_GN like '%' + #deceasedFirstName + '%' AND PR_NAME_SURN like '%' + #deceasedLastName + '%' AND EVENT_PARISH like '%' + #ParishOfDeath+ '%' AND EVENT_YEAR like '%' + #YearOfDeath+ '%' AND EVENT_TYPE like '%' + #TypeDeath+ '%' AND FS_IMAGE_ID like '%' + #ImgLocation+ '%')";
SqlCommand command = new SqlCommand(str, connection);
command.Parameters.Add("#deceasedFirstName", SqlDbType.NVarChar).Value = DeathFirstNametbox.Text;
command.Parameters.Add("#deceasedLastName", SqlDbType.NVarChar).Value = DeathLastNametbox.Text;
command.Parameters.Add("#ParishOfDeath", SqlDbType.NVarChar).Value = ParishoDeathtbox.Text;
command.Parameters.Add("#YearOfDeath", SqlDbType.NVarChar).Value = YearofDeathtbox.Text;
command.Parameters.Add("#TypeDeath", SqlDbType.NVarChar).Value = type_Death.Text;
command.Parameters.Add("#ImgLocation", SqlDbType.NVarChar).Value = "";
command.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataSet ds = new DataSet();
sda.Fill(ds, "PR_NAME_GN");
sda.Fill(ds, "PR_NAME_SURN");
sda.Fill(ds, "EVENT_PARISH");
sda.Fill(ds, "EVENT_YEAR");
sda.Fill(ds, "EVENT_TYPE");
sda.Fill(ds, "FS_IMAGE_ID");
GridView1.DataSource = ds;
GridView1.DataBind();
connection.Close();
I need recommendation on how to rework the sql statement. I am kinda new to this so please bear with me.
Remove the leading % wildcard after the LIKE keyword so that only values starting with the specified value will be returned:
String str = "SELECT PR_NAME_GN, PR_NAME_SURN, EVENT_PARISH, EVENT_YEAR, EVENT_TYPE, FS_IMAGE_ID FROM Jam01 WHERE (PR_NAME_GN LIKE #deceasedFirstName + '%' AND PR_NAME_SURN LIKE #deceasedLastName + '%' AND EVENT_PARISH like #ParishOfDeath + '%' AND EVENT_YEAR LIKE #YearOfDeath+ '%' AND EVENT_TYPE LIKE #TypeDeath+ '%' AND FS_IMAGE_ID LIKE #ImgLocation + '%');";
I am trying to get search query
Its in asp.net c# please help me for search query.
protected void btnreg_Click(object sender, EventArgs e)
{
string search = query.Text;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE search LIKE '%' + nor + '%' OR recipe LIKE '%' + search + '%' OR ingredients LIKE '%' + search + '%' OR type_of_food LIKE '%' + search + '%' OR type_of_meal LIKE '%' + search + '%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}}
I suppose 'nor' is a column name in your table .. try the following :-
protected void btnreg_Click(object sender, EventArgs e)
{
string search = query.Text;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '%'" + search + "'%' OR recipe LIKE '%' "+ search + "'%' OR ingredients LIKE '%' "+ search + "'%' OR type_of_food LIKE '%' "+ search + "'%' OR type_of_meal LIKE '%' "+ search +" '%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}
}
Actually you cannot enclose the varibale search inside the "double quotes" tag .
Hope this helps you .
Cheers !
Why not use Parameterized Queries !
E.g
var command = "SELECT * FROM recipe WHERE recipe LIKE '% #Receipe %'";
var cmd= new SqlCommand(command , yourconnetion);
cmd.Parameters["#Receipe "].Value =query.Text;
OR
cmd.Parameters.AddWithValue("#Receipe ",query.Text);
Read more about How and Why to Use Parameterized Queries
Finally I got the right one, it goes like this.
Although thanks for help guys.
protected void btnreg_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '%" + query.Text + "%' OR recipe LIKE '%" + query.Text + "%' OR ingredients LIKE '%" + query.Text + "%' OR type_of_food LIKE '%" + query.Text + "%' OR type_of_meal LIKE '%" + query.Text + "%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}
Use `Parametarized` and `Using{}` statement to auto dispose and close connection
using( SqlConnection objConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
objConnection.Open();
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '% #query %'" , con))
DataTable dt= new DataTable();
da.SelectCommand.Parameters.AddWithValue("#query",query.Text);
da.Fill(dt);
}
catch(System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
I am very new to sqlite and c# and trying exporting a csv file to sqlite database using dataset.
but I get this error.
SQL logic error or missing database
no such column: P17JAW
code:
string strFileName = "I:/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source= C:/Users/WebMobility.db; Version=3;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "'," + VRM + "," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
CSV FILE CONTAINS
Id,VehicleRegistration,TicketScore
21,P17JAW,1
22,K1WOM,1
23,m4npr,4
25,G7EPS,4
Your problem is with the single quotes missing for VRM your query should be like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
( '" + Id + "','" + VRM + "'," + Points + ")";
//^^ ^^
From the values it appears that ID is of integer type, you can remove single quotes around ID.
You should parameterized your query that will save your from these errors. I am not sure if parameters are supported by SQLiteCommand if they are you can do something like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
(#Id,#VRM,#Points)";
and then
command.Parameters.AddWithValue("#id", Id);
command.Parameters.AddWithValue("#VRM", VRM);
command.Parameters.AddWithValue("#Points", Points);