Iam trying to figure out a way to select a value on a comboBox which would then be used for and mysql command.
Iam new to coding in c# so i got know clue where my mistake should be.. searched some hours now and found nothing.
It is supposed to be used as an filter to search through a huge stack of customers data to for example only show customers living in Berlin, oder working as...
if (checkBoxrecruitingsearch2.Checked)
{
MySqlCommand cmddtschichten = conn.CreateCommand();
cmddtschichten.CommandType = CommandType.Text;
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE '"+ comboBoxrecruitingfilter.Text +"' = '" + textBoxrecruitingsearch.Text + "' and '" + comboBoxrecruitingsearch2.Text + "' = '" + textBoxrecruitingsearch2.Text + "'";
cmddtschichten.ExecuteNonQuery();
DataTable dtschichten = new DataTable();
MySqlDataAdapter cmddaschichten = new MySqlDataAdapter(cmddtschichten);
cmddaschichten.Fill(dtschichten);
dtschichten.Columns["id"].ColumnName = "Bewerber ID";
dtschichten.Columns["Wohnort"].ColumnName = "Wohnort";
dtschichten.Columns["Berufsbezeichnung"].ColumnName = "Berufsbezeichnung";
BindingSource bSourceschichten = new BindingSource();
bSourceschichten.DataSource = dtschichten;
dataGridViewrecruitingsearchresult.DataSource = bSourceschichten;
cmddaschichten.Update(dtschichten);
}
else
{
MySqlCommand cmddtschichten = conn.CreateCommand();
cmddtschichten.CommandType = CommandType.Text;
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE '"+ comboBoxrecruitingfilter.Text +"' = '" + textBoxrecruitingsearch.Text + "'";
cmddtschichten.ExecuteNonQuery();
DataTable dtschichten = new DataTable();
MySqlDataAdapter cmddaschichten = new MySqlDataAdapter(cmddtschichten);
cmddaschichten.Fill(dtschichten);
dtschichten.Columns["id"].ColumnName = "Bewerber ID";
dtschichten.Columns["Wohnort"].ColumnName = "Wohnort";
dtschichten.Columns["Berufsbezeichnung"].ColumnName = "Berufsbezeichnung";
BindingSource bSourceschichten = new BindingSource();
bSourceschichten.DataSource = dtschichten;
dataGridViewrecruitingsearchresult.DataSource = bSourceschichten;
cmddaschichten.Update(dtschichten);
}
the expected result would be to get back all "bewerber" where column (choosen on comboBoxrecruitingfilter) equals textBoxrecuitingsearch
I do get shown a list with all entry's when executing with empty text and combobox, otherwise it shows nothing
SOLUTION
If I remember correctly mysql does have a specific column name delimiter " ` " but in your where you are using " ' ". Very similar but different characters
WHERE ' "+ comboBoxrecruitingfilter.Text +" ' = '" + textBoxrecruitingsearch.Text + " '
should be:
WHERE ` "+ comboBoxrecruitingfilter.Text +" ` = '" + textBoxrecruitingsearch.Text + " '
As a side note, your code is subject to SQL Injection, if your users are not trusted you have a security problem/could be hacked. Should move to parametrized queries instead.
Remove the ' around the field name in the where clause:
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE "+ comboBoxrecruitingfilter.Text +" = '" + textBoxrecruitingsearch.Text + "' and " + comboBoxrecruitingsearch2.Text + " = '" + textBoxrecruitingsearch2.Text + "'";
and
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE "+ comboBoxrecruitingfilter.Text +" = '" + textBoxrecruitingsearch.Text + "'";
If you have space between your field names, you can use one of the following:
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE `"+ comboBoxrecruitingfilter.Text +"` = '" + textBoxrecruitingsearch.Text + "'";
or
cmddtschichten.CommandText = "SELECT id, Wohnort, Berufsbezeichnung FROM bewerber WHERE ["+ comboBoxrecruitingfilter.Text +"] = '" + textBoxrecruitingsearch.Text + "'";
Related
I am trying to read an integer from a SQL Server database by text in comboboxes.
I get a "Syntax error" "near" my Table name "Seeweg". The debugger does not highlight the line, where the error happens.
The column with the value I like to get is named seadistance. The other columns, by which to sort are start and ziel.
They get sorted by the values written in the comboboxes.
To reproduce this procedure I inserted the code into a class and called the instance by a button named btnSea.
I already searched for similar problems, but I could not find any syntax errors concerning the string implementation. The column names are correct.
//The Button
private void btnSea_Click(object sender, EventArgs e)
{
Entnehmen CO2 = new Entnehmen();
int Dist = CO2.Werte("Seeweg", "start", "ziel", "seadistance", comboSeaOrig.Text, comboSeaDest.Text);
MessageBox.Show(Dist.ToString());
}
//The class
class Entnehmen
{
public int Werte(string Tabelle, string Reihe1, string Reihe2, string Wertereihe, string WertReihe1, string WertReihe2)
{
int Wert = 0;
string myConnection = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
using (SqlConnection myConn = new SqlConnection(myConnection))
{
myConn.Open();
SqlCommand SelectCommand = new SqlCommand("SELECT '" + Wertereihe + "' FROM '" + Tabelle + "' WHERE '" + Reihe1 + "' = '" + WertReihe1 + "' AND '" + Reihe2 + "' = '" + WertReihe2 + "' ; ", myConn);
Wert = (int)SelectCommand.ExecuteScalar();
}
return Wert;
}
}
}
I expect the value to be given back. Before that happens, I get the error:
Incorrect syntex near 'Seeweg'
Where is the syntax mistake? Any help is appreciated =)
You are generating something like:
SELECT 'seadistance' FROM 'Seeweg' WHERE 'start' = 'aa' AND 'ziel' = 'bbb'
This is not a valid T-SQL statement. Correct your quotes in columns and tables variables.
This is a suggestion of how you can write your T-SQL statemant based on your code:
SqlCommand SelectCommand = new SqlCommand("SELECT " + Wertereihe + " FROM " + Tabelle + " WHERE " + Reihe1 + " = '" + WertReihe1 + "' AND " + Reihe2 + " = '" + WertReihe2 + "' ; ", myConn);
Tried to move data from one form to another and there is a problem with the table. Yes I found such themes with a mistake, and tried to correct himself, but something went wrong.
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('"+ tName.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + cbName.Text + "' and Stage = '" + cbStage.Text + "'), '" + tSurname.Text + "', '" + tMiddle.Text + "', '" + tPas.Text + "', '" + cbClinic.Text + "', '" + tAge.Text + "')", conn);
conn.Open();
DataSet ds = new DataSet();
//ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
comm.Fill(ds);
Form1 form = new Form1();
form.DataGrid.DataSource = ds.Tables[0]; //?
}
string connectionString = "Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('" + metroTextBox1.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + metroComboBox1.Text + "' and Stage = '" + metroComboBox2.Text + "'), '" + metroTextBox2.Text + "', '" + metroTextBox3.Text + "', '" + maskedTextBox1.Text + "', '" + metroComboBox3.Text + "', '" + metroTextBox5.Text + "')";
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Added");
//here is a DataSet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
transaction.Rollback();
}
}
You are expecting results to be returned from your query, but what you do is just INSERT statement.
For inserting values you should use ExecuteNonQuery method of SqlCommand (see this for reference).
Then, assign another command: SELECT to get the results, then you can fill DataSet with the result and then you can fill DataGridView with it.
Also: you are rpone to SQL injection, use parametrized query to prevent yourself from such threat (see this for reference).
I have a SQL statement for querying in MS Access. I want to get the result of the transaction between dates.
This is my code:
DateTime pFromNew = Convert.ToDateTime(this.dateTimePicker1.Value.ToString("yyyy-MM-dd"));
DateTime pToNew = Convert.ToDateTime(this.dateTimePicker2.Value.ToString("yyyy-MM-dd"));
string pFrom = "#" + pFromNew.ToString() + "#";
string pTo = "#" + pToNew.ToString() + "#";
chrTrans.Series["Class"].Points.Clear();
oconn.Open();
OleDbCommand cmd = oconn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
//+ "' and valuedate between '"+ this.dateTimePicker1.Text +"' and '"+ this.dateTimePicker2.Text +"'";
cmd.ExecuteNonQuery();
What is wrong with this statement?
I always get this error:
DATA Type mismatch in criteria expression.
Remove the single quotes you have in your string... I will show you...
This line:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
Should be:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo;
The reason is that you already concatenated a # symbol around your date strings--and the single quote thus is not needed.
You are making this too complicated, converting back and forth three times.
It can be reduced to:
string pFrom = "#" + this.dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "#";
string pTo = "#" + this.dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd") + "#";
// snip
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo + "";
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("UPDATE tbl_delivery SET (Supplier, InvoiceNumber, DRNumber, PONumber, ItemQty, ReceivedDate, Address, Contact, ReceivedBy, AssetNumber) (Supplier ='" + this.supplierTextBox.Text + "',InvoiceNumber ='" + this.invoiceNumberTextBox.Text + "',DRNumber ='" + this.dRNumberTextBox.Text + "',PONumber ='" + this.pONumberTextBox.Text + "',ItemQty ='" + this.itemQtyTextBox.Text + "',ReceivedDate ='" + this.receivedDateDateTimePicker.Text + "',Address ='" + this.addressTextBox.Text + "',Contact ='" + this.contactTextBox.Text + "',ReceivedBy ='" + this.receivedByTextBox.Text + "',AssetNumber ='" + this.assetNumberTextBox.Text + "'", conn);
cmd.CommandType = CommandType.Text;
OdbcDataAdapter ds = new OdbcDataAdapter(cmd);
ds.SelectCommand = cmd;
System.Data.DataTable dtable = new System.Data.DataTable();
ds.Fill(dtable);
tbl_deliveryDataGridView.DataSource = dtable;
conn.Open();
cmd.ExecuteNonQuery();
update button won't work, please check if my update statement is correct. i am using c#..............
I think your Query is incorrect.
OdbcConnection conn = new OdbcConnection();
conn.ConnectionString =
"Dsn=mdc;" +
"Uid=root;" +
"Pwd=;";
OdbcCommand cmd = new OdbcCommand("UPDATE tbl_delivery SET Supplier ='" + this.supplierTextBox.Text + "',InvoiceNumber ='" + this.invoiceNumberTextBox.Text + "',DRNumber ='" + this.dRNumberTextBox.Text + "',PONumber ='" + this.pONumberTextBox.Text + "',ItemQty ='" + this.itemQtyTextBox.Text + "',ReceivedDate ='" + this.receivedDateDateTimePicker.Text + "',Address ='" + this.addressTextBox.Text + "',Contact ='" + this.contactTextBox.Text + "',ReceivedBy ='" + this.receivedByTextBox.Text + "',AssetNumber ='" + this.assetNumberTextBox.Text + "'", conn);
Then where is your Where clause? just add it on the query
Then
cmd.ExecuteNonQuery();
ds= newodbcDataAdapter(cmd);
ds.Fill(dtable);
tbl_deliveryDataGridView.ItemsSource = dtable.DefaultView;
You better execute your query first before displaying it to your datagrid for that you'll able to see the updated table.
guy how can i insert the value of checkbox in access database or any database.
i tried any of this sql statement but it still give me error: OleDbException was Unhandled. Data type mismatch in criteria expression. and it's pointing to myData = myCommand.ExecuteReader();
note that allowviewpsr is a boolean type of field in ms access database or the one with YES/NO. :) chkviewpsr is mycheckbox
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked.Value + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
also this:
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
and also this:
SQL = "UPDATE `RUsers` SET `allowviewpsr` = '" + chkviewpsr + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
and here's my connector:
myCommand.CommandText = SQL;
myCommand.Connection = MyNewOleDbConnection;
myAdapter.SelectCommand = myCommand;
myData = myCommand.ExecuteReader();
EDITED:
hi anandkumar thanks for the quick replay i tried NonQuery but it gives same error as above
SQL = "UPDATE `RWMUsers` SET `allowviewpsr` = '" + chkviewpsr.IsChecked.Value + "' WHERE `idnum`= '" + txtblkuserid.Text + "' AND `fullname`= '" + txtblkusername.Text + "'";
myCommand.CommandText = SQL;
myCommand.Connection = MyNewOleDbConnection;
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
Snapshot of my Access Database :(
Instead of
myAdapter.SelectCommand = myCommand;
myCommand.ExecuteReader();
Use
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
Reference:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.updatecommand.aspx