I have a string with values like:
a,b,c,d,e
The idea is to use an sql command to search an array for entries.
The sql is:
select * from pelates where Onoma in (#giorti)
I am turning the a,b,c,d,e to 'a','b','c','d','e' an then i replace the #giorti value with the previus string to fill a datagridview.
The problem is that the datagridview stays empty unless i edit the sql statement and give a value manually like:
select * from pelates where Onoma in ('Bampis')
if i do so the results come like normal. Please advice ,i think there an encoding problem because the data are in Greek
Here is my code:
//Diaxorismos onomaton pou giortazoun
String giorti = label2.Text;
String[] name = giorti.Split(',');
for (int i = 0; i < name.Length; i++)
{
StringBuilder sb = new StringBuilder(name[i]);
sb.Insert(0, "'");
sb.Append("'");
name[i] = sb.ToString();
name[i] = name[i];
}
String finalName = String.Join(",", name);
finalName = finalName.Replace(" ", "");
textBox1.Text = finalName;
//
showPelatesPouGiortazounCommand = login.connection.CreateCommand();
showPelatesPouGiortazounCommand.CommandText = "select * from pelates where Onoma in (#giorti)";
showPelatesPouGiortazounCommand.Parameters.AddWithValue("#giorti", System.Text.Encoding.UTF8.GetBytes(finalName));
getPelatesPouGiortazounAdapter = new MySqlDataAdapter(showPelatesPouGiortazounCommand);
pelatesPouGiortazounDataset = new DataSet();
getPelatesPouGiortazounAdapter.Fill(pelatesPouGiortazounDataset);
dataGridView1.DataSource = pelatesPouGiortazounDataset.Tables[0].DefaultView;
Use FIND_IN_SET function to search in a comma separated list,
or prepare and bind as many parameters as you have values in the string.
select * from pelates where FIND_IN_SET(Onoma, #giorti)
http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_find-in-set
Thanks a lot fellows!
With the above addition my code works great!
Here is the final code:
String giorti = label2.Text;
String[] name = giorti.Split(',');
String finalName = label2.Text;
finalName = finalName.Replace(" ", "");
textBox1.Text = finalName;
showPelatesPouGiortazounCommand = login.connection.CreateCommand();
showPelatesPouGiortazounCommand.CommandText = "select * from pelates where FIND_IN_SET(Onoma, #giorti)";
showPelatesPouGiortazounCommand.Parameters.AddWithValue("#giorti", System.Text.Encoding.UTF8.GetBytes(finalName));
getPelatesPouGiortazounAdapter = new MySqlDataAdapter(showPelatesPouGiortazounCommand);
pelatesPouGiortazounDataset = new DataSet();
getPelatesPouGiortazounAdapter.Fill(pelatesPouGiortazounDataset);
dataGridView1.DataSource = pelatesPouGiortazounDataset.Tables[0].DefaultView;
Related
I have made a small purchasing application. The user selects a couple of Orders and clicks 'SEND EMAIL'. Email gets created with data from the database for those specific orders.
This is how I am doing it right now:
string mailbod = "Following are Orders that need your attention: ";
mailbod=od.mailbody(orderid,mailbod);//Calling the method that sets up the string
public string mailbody(List<int>oids,string mailbod)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
string output = "";
using (SqlConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("TESTDB")))
{
StringBuilder sb = new StringBuilder("Select Distinct a.VEND_NAME,b.* from dbo.Purch_Vendor a inner join dbo.purch_order b on a.VENDOR_ID=b.VENDOR_ID left join dbo.purch_item c on b.ORDER_ID=c.ORDER_ID Where ");
if (oids.Count > 0)
{
foreach(int x in oids)
{
sb.Append("b.ORDER_ID" + "=" + x + " OR ");
}
sb.Length--;
sb.Length--;
sb.Length--;
SqlCommand command = new SqlCommand(sb.ToString(), connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
foreach (DataRow x in dtRecord.Rows)
{
//' Loop through each column. '
for (int i=0;i<dtRecord.Columns.Count; i++)
{// ' Output the value of each column's data.
sw.Write(x[i].ToString() + ", ");
}
output = sw.ToString();
//' Trim off the trailing ", ", so the output looks correct. '
if (output.Length > 2)
{
output = output.Substring(0, output.Length - 2);
}
//' Display the row in the console window. '
Console.WriteLine(output);
}
return output;
}
else
{
return "";
}
}
}
The output that gets emailed looks like this:
Amazon, 2, 1, 2/20/2020 12:00:00 AM, kjhgg, 34.400, N, awefwef
The output I would like to get:
Following are the Orders that need your attention:
How can I get this to work as close as possible? Any ideas appreciated
I´m trying to get the correct string from a wpf datagrid clicked cell that i will use in a sql select statement to a second wpf datagrid.
When entering a static string value it will work, but not from a dynamic string. What is wrong with my code?
private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = 'L002BO4'";
}
When entering the string in the sql statement it works like a charm, but ofcourse i want the dynamic string returned from the large database work as well.
Please do not concatenate strings in SQL statements. Use parameters. Check your database for the correct data type of the BarCode column.
private void DataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataTable dt = new DataTable();
DataRowView row = (DataRowView)dataGrid1.SelectedItems[0];
string barcode_string = row["BarCode"].ToString();
//string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = '" + barcode_string + "'";
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = #BarCode;";
using (SqlConnection cn = new SqlConnection("Your connection string"))
{
SqlCommand cmd = new SqlCommand(barcode_detail, cn);
cmd.Parameters.Add("#BarCode", System.Data.SqlDbType.VarChar).Value = barcode_string;
cn.Open();
dt.Load(cmd.ExecuteReader());
//use the data in the data table
}
}
EDIT
Test the strings. Add using System.Diagnostics to use Debug.Print
String literal = "L002BO4";
String variable = row["BarCode"].ToString();
if (literal.Length == variable.Length)
Debug.Print("The length of the strings match");
else
Debug.Print("The lengths do not match");
Char[] variableArray = variable.ToCharArray();
Char[] literalArray = literal.ToCharArray();
for (int index =0; index<literalArray.Length; index++)
{
if (variableArray[index] == literalArray[index])
Debug.Print($"index {index} matches");
else
Debug.Print($"index {index} does not match");
}
You just missed one " at the last of your query. Try this
string barcode_detail = "SELECT BarCode, PCBGUID
FROM TB_AOIResult WHERE
BarCode = "+"\'" +barcode_string + "\'";
Can you try like below
string barcode_detail = "SELECT BarCode, PCBGUID FROM TB_AOIResult WHERE BarCode = "+ barcode_string;
I try to delete some rows from a table in an access database file via C#.
This attempt fails with no error which leads me to the conclusion that I have a valid query with incorrect data.
I tried to see if I can query the data with a select statement from my code and I can narrow the problem down to the parameters.
The statement should look as follows
SELECT * FROM tbIndex where pguid in ('4a651816-e15b-4c6a-85c4-74033ca6c423', '0add7bff-a22f-4238-9c7f-e1ff4ed3c7e2', '742fae8b-2692-4a6f-802c-848fad570696', '5e6b65de-2403-4800-a47d-e57c7bd8e0a6')
I tried two different ways*(dbCmd2 and dbCmd3)* from which the first*(dbCmd2)* works but is, due to injection problems, not my prefered solution.
using (OleDbCommand dbCmd2 = new OleDbCommand { Connection = m_Connection })
{
dbCmd2.CommandText = "SELECT * FROM tbIndex where pguid in ("+pguid+")";
using (DbDataReader reader = dbCmd2.ExecuteReader())
{
List<object[]> readValuesFromIndex = new List<object[]>();
while (reader.Read())
{
//Point reached
object[] arr = new object[reader.VisibleFieldCount];
reader.GetValues(arr);
//...
}
reader.Close();
}
using (OleDbCommand dbCmd3 = new OleDbCommand { Connection = m_Connection })
{
dbCmd3.CommandText = "SELECT * FROM tbIndex where pguid in (#pguid)";
dbCmd3.Parameters.Add("#pguid", OleDbType.VarChar).Value = pguid;
using (DbDataReader reader = dbCmd3.ExecuteReader())
{
List<object[]> readValuesFromIndex = new List<object[]>();
while (reader.Read())
{
//Point not reached
object[] arr = new object[reader.VisibleFieldCount];
reader.GetValues(arr);
//...
}
reader.Close();
}
}
Note that pguid is set to "'4a651816-e15b-4c6a-85c4-74033ca6c423', '0add7bff-a22f-4238-9c7f-e1ff4ed3c7e2', '742fae8b-2692-4a6f-802c-848fad570696', '5e6b65de-2403-4800-a47d-e57c7bd8e0a6'".
I always thought that the second option would simply replace the parameter in a safe manner but this is obviously not the case.
My question is:
Why doesn't the second option return any values?
A parameter always is a single value.
An in clause requires multiple values, separated by comma's.
You can do something like the following to pass them like separate parameters:
string[] guids = pguid.Split(',');
string sqlin = "";
int paramno = -1;
foreach (var guid in guids)
{
parametercount ++;
sqlin = sqlin + "#Param" + (string)parametercount; + ","
}
dbCmd3.CommandText = "SELECT * FROM tbIndex where pguid in (" + sqlin.Substring(0, sqlin.Length-1) + ")";
for(int i = 0; i <= parametercount; i++){
dbCmd3.Parameters.Add("#Param" + (string)i, OleDbType.VarChar).Value = guids[i].Replace("'", "");
}
This is my second question here in StackOverflow and this is where im stuck
i want to loop every value in a multiline textbox and pass it as query criteria then fill my DataGridView with the result (multiple results).
The problem is. that i cannot pass more than 1 value from the textbox. i can execute correctly the query but its not looping correctly as it only shows the result of the first value in my data grid and i want the data(result) from every line in the textbox
my code is
for (int i = 0; i < textBox1.Lines.Length; i++)
{
Connect();
OracleCommand cmd = new OracleCommand();
OracleDataAdapter adapter = new OracleDataAdapter();
DataTable dt = new DataTable();
cmd = new OracleCommand(OraSql + OraSql2 + orasql3 + OraSql4, con);
adapter = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dataGridView1.Rows.Add
(
row[0].ToString(),
row[1].ToString(),
row[2].ToString(),
row[3].ToString(),
row[4].ToString(),
row[5].ToString()
);
}
}
i hope that i explained myself correctly here
Thank you!
this is my query
string OraSql = #"SELECT r.ixkitl ""Parent Part Number"",
r.ixlitm ""Component Part Number"",
i.imdsc1 ""Description"",
SUM((r.ixqnty/10000)) ""Qty per Harness"",
To_date(r.ixefff+1900000, 'YYYYDDD') ""Effective From Date"",
To_date(r.ixefft+1900000, 'YYYYDDD') ""Effective Thru Date"",
r.ixtbm ""Bill Type"",
r.ixmmcu ""Branch Plt""
FROM proddta.f3002 r,
proddta.f4101 i";
string OraSql2 = #"
WHERE (i.imlitm IN '" + textBoxX1.Text.ToString() + "'AND i.imitm = r.ixkit)";
string orasql3 = #"
AND (r.ixmmcu = ' 3320' AND r.ixtbm = 'M ')";
string OraSql4 = #"
AND r.ixefff <= (to_char(SYSDATE, 'YYYYDDD')-1900000)
AND r.ixefft >= (to_char(SYSDATE, 'YYYYDDD')-1900000)
GROUP BY r.ixkitl,
r.ixlitm,
r.ixqnty,
r.ixtbm,
r.ixmmcu,
r.ixefff,
r.ixefft,
i.imdsc1
ORDER BY r.ixkitl,
r.ixlitm";
This is my query
SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK)
WHERE MPRO.Estado0154 = 'QUEUED'
AND F1IdWI02140154<>'VOICEMAIL'
AND F1Camp02930154 = 'Support'
please notice that i have AND F1Camp02930154 = 'Support'
Now I have a list like this:
List<string> compaines = new List<string>();
the values in this list should be in this conidtion AND F1Camp02930154 = 'Support'
for example if the list is empty, i will get an empty result, but if the list has just one value which is Support the query will be
AND F1Camp02930154 = 'Support'
but if the list has two vaules which are Support and Sales then the query will be
AND F1Camp02930154 = 'Support' and `Sales`
how to do that please in c#
where I already have this:
string queryString = "SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) WHERE MPRO.Estado0154 = 'QUEUED' AND F1IdWI02140154<>'VOICEMAIL'";
Update 1
After # Gordon Linoff comment
I tried this:
List<string> compaines = new List<string>();
string queryString = "SELECT COUNT(MPRO.OriDes0154) 'QueueCalls' FROM MMProdat.dbo.InstTaWf0154 MPRO WITH(NOLOCK) WHERE MPRO.Estado0154 = 'QUEUED' AND F1IdWI02140154<>'VOICEMAIL' AND F1Camp02930154 IN (";
for (int i = 0; i < compaines.Count(); i++) {
queryString += "'" + compaines[i] + "'";
}
queryString += ")";
You can use String.Join() to construct IN () clause, for example :
var companies = new List<string>() { "Support", "Sales" };
string inClause = String.Format(" IN ('{0}')", String.Join("', '", companies));
Console.WriteLine("AND F1Camp02930154" + inClause);
//output :
//AND F1Camp02930154 IN ('Support', 'Sales')