Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I'm coding a small program with C# to watch my organization's cars and I use code below to update value but it didn't work when I apply it.
OleDbCommand updateCommand = new OleDbCommand("UPDATE Mqar SET [Car_Type] = #Car_Type,[Model] = #Model,[chase_nu] = #chase_nu,[Engin_Nu] = #Engin_Nu,[Car_nu] = #Car_nu,[Car_State] = #Car_State,[Draiver_Name] = #Draiver_Name,WHERE [ID] = #ID", conn);
conn.Open();
updateCommand.Parameters.AddWithValue("#Car_Type", textBox1.Text);
updateCommand.Parameters.AddWithValue("#Model", textBox2.Text);
updateCommand.Parameters.AddWithValue("#chase_nu", textBox3.Text);
updateCommand.Parameters.AddWithValue("#Engin_Nu", textBox4.Text);
updateCommand.Parameters.AddWithValue("#Car_nu", textBox5.Text);
updateCommand.Parameters.AddWithValue("#Car_State", comboBox1.Text);
updateCommand.Parameters.AddWithValue("#Draiver_Name", textBox6.Text);
//updateCommand.Parameters.AddWithValue("#ID", Convert.ToInt32(textBox7.Text));
//conn.Open();
updateCommand.ExecuteNonQuery();
conn.Close();
MessageBox.Show("تم تعديل بيانات الالية بنجاح");
connaction();
The update statement is not correct because there is a comma before the where keyword.
Change the SQL like this:
UPDATE Mqar SET [Car_Type] = #Car_Type,[Model] = #Model,[chase_nu] = #chase_nu,[Engin_Nu] = #Engin_Nu,[Car_nu] = #Car_nu,[Car_State] = #Car_State,[Draiver_Name] = #Draiver_Name WHERE [ID] = #ID
Notice I removed a comma before ,WHERE => WHERE
Also notice that there is an #ID parameter, so you need to pass that too, so uncomment this line:
updateCommand.Parameters.AddWithValue("#ID", Convert.ToInt32(textBox7.Text));
Extra advice (not an answer to your question):
You need to name your variables/input elements in a way that reflects that they are used for.
For example, textBox1 is a bad name because the name does not tell you what it is supposed to be, is it a Car Name? An ID? A model name?
You should rename all the input elements (text boxes and combo boxes) to something meaningful like:
textBox1 => carTypeText
comboxBox1 => carStateComboBox
The clarity you will gain from properly named variables will help you avoid bugs.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Im trying to retrieve no of rows from sql based user input & display in gridview
Please help!
Int32 text = Convert.ToInt32(this.Txtusers.Text);
con.Open();
cmd = new SqlCommand("select TOP '" + text + "' * from Avaya_Id where LOB = '" + DDLOB.SelectedItem.Value + "' and Status = 'Unassigned'", con);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
Here is how it should be written.
int text;
if(int.TryParse(this.Txtusers.Text, out text)
{
using(var con = new SqlConnection(connectionString)
{
using(var cmd = new SqlCommand("select TOP (#top) * from Avaya_Id where LOB = #LOB and Status = 'Unassigned'", con))
{
cmd.Parameters.Add("#top", SqlDbType.Int).Value = text;
cmd.Parameters.Add("#LOB", SqlDbType.Int).Value = DDLOB.SelectedItem.Value;
con.Open();
using(var rdr = cmd.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Points of interest:
Using parameters to avoid the risk of Sql Injection.
Changed Convert.ToInt32 to int.TryParse. Never trust user input.
Use the using statement for every instance that implements the IDisposable interface.
Please note that using top x without an order by clause means you get x arbitrary records from the database - since database tables are unordered by nature and the only way to ensure the order of the rows returned from a select statement is to use the order by clause.
Please note I've guessed that the second parameter is an int, if it's not, change the data type.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I tried to write a code which will count rows in MySQL , same as combobox-selected text.
For example in my MySQL database,i have a table(ogrencikayit) and in this table i have several columns.In my combobox there are 2 different selection which allows to select student class.When user select the class in combobox , label has to show count of total student in selected class.Here is my code;
DB database = new DB();
int kayitsayisi = -1;
MySqlCommand cmd = new MySqlCommand("Select count(*) from ogrencikayit Where ogrsinif ="+comboBox3.Text.ToUpper()+"" , database.baglanti);
database.baglanti.Open();
kayitsayisi = Convert.ToInt32(cmd.ExecuteScalar());
string kayitt = kayitsayisi.ToString();
label24.Text = kayitt;
Shortly; i try to find a code that it will read the name of the class name from combobox than it will search in database that how many student belongs to that class and it will show it to the label.
It says Invalid column "class name" in where clause.
that's cause you are missing single quote around the value and thus it's taking it as a column name. it should be like below
Where ogrsinif ='"+comboBox3.Text.ToUpper()+"'"
Again, always use parameterized query instead of concatenating your user input.
MySqlCommand cmd = new MySqlCommand("Select count(*) from ogrencikayit Where ogrsinif = #ogrsinif" , database.baglanti);
cmd.Parameters.Add("#ogrsinif", SqlDbType.VarChar).Value=comboBox3.Text;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am creating a form for alerting the user that the stock for this item in the database is getting the limit or passed right through the limit.
this is my code for checking the quantity of a certain stock
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from tbl_BloodChemistry where Glucose = "+123+" ";
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
It's not actually the answer, but you have no reason to retrieve all data to collect count of rows. Use SQL COUNT and ExecuteScalar() for this.
Also, it's important to use command Parameters to your query. Don't ever build a query in your way! The input variable, Glucose, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into inputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.
Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.
Using parameterized queries is a three step process:
Construct the SqlCommand command string with parameters.
Declare a SqlParameter object, assigning values as appropriate.
Assign the SqlParameter object to the SqlCommand object's Parameters property.
var glucoseFilterValue = "123";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select count(*) from tbl_BloodChemistry where Glucose = #Glucose";
cmd.Parameters.AddWithValue("#Glucose", glucoseFilterValue);
var count = (int) cmd.ExecuteScalar();
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
Then you'll make your code more clean and prevent extra loading to your communication channel.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to enter the value of a textbox in c# into a field in a database that I have in access. For some reason I keep getting the error saying:
'An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.'
Can't quite see what is wrong, this is the first time I have attempted to do this in a project so I am not too experienced with it. This is my code:
OleDbConnection connection = new OleDbConnection(CONNECTION STRING GOES HERE);
connection.Open();
string playerName = textBox[i].Text;
string query = "INSERT INTO (TotalPlayerName)(Player Name) VALUES(" + playerName + ")";
OleDbCommand command = new OleDbCommand(query, connection);
command.ExecuteNonQuery();
if it helps then the database is called 'Database' the table is called 'TotalPlayerName' and the field is called 'Player Name'
The correct code to do your task is
string cmdText = "INSERT INTO TotalPlayerName ([Player Name]) VALUES(?)";
using(OleDbConnection connection = new OleDbConnection(...))
using(OleDbCommand command = new OleDbCommand(cmdText, connection))
{
connection.Open();
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = textBox[i].Text;
int result = command.ExecuteNonQuery();
if(result > 0)
MessageBox.Show("Record Inserted");
else
MessageBox.Show("Failure to insert");
}
This approach fixes three problems:
The connection and the command object should be disposed at the end
(see using statement)
Every value that you need to pass to the query should be passed as
parameter
If a field name (or table name) has embedded spaces you should enclose
it between square brackets
(The messages below the ExecuteNonQuery are there only as an example to check the return value of ExecuteNonQuery)
Remember also that if your table has more than this field and some of the other fields don't accept null values you should provide some value also for them.
For example
string cmdText = #"INSERT INTO TotalPlayerName ([Player Name], FieldB)
VALUES(?, ?)";
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = textBox[i].Text;
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = "ValueForFieldB";
Just remember to strictly follow the order of the ? when you add your parameter values
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to populate a dropdown , where I want the default selected value to be the sysdate selected. For example if I have 4 results in the dropdown
Wednesday,January 22,2013
Thursday,January 23,2013
Friday,January 24,2013
Saturday,January 25,2013
I want todays date Friday,January 24,2013 to be the default selected value. Now to achieve that I have written code like below in my method.
string DateofNow = DateTime.Now.ToString("dddd,MMMM dd,yyyy");
DataTable table = new DataTable();
string sqlQuery = "select distinct duty_date from duty_rota where duty_date BETWEEN SYSDATE - 40 AND SYSDATE + 365 order by duty_date";
using (OracleConnection conn = new AppConfig().GetConnection())
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
DropDownList1.DataSource = table;
DropDownList1.DataValueField = "duty_date";
DropDownList1.DataTextField = "duty_date";
DropDownList1.DataTextFormatString = "{0:dddd,MMMM dd,yyyy}";
DropDownList1.DataBind();
DropDownList1.Items.FindByText(DateofNow).Selected = true;
But I am getting "Object reference not set to an instance of an object" Error. I am clueless where I am going wrong exactly. Can somebody please help me in this.
Assuming you run the above code today, it's because DateofNow value is Friday,January 24,2014 but none of the DropDownList items has the exact same value. Since the query result may not contain today's date, I would suggest changing this line:
DropDownList1.Items.FindByText(DateofNow).Selected = true;
to this:
if (DropDownList1.Items.FindByText(DateofNow) != null)
{
DropDownList1.Items.FindByText(DateofNow).Selected = true;
}
so if the query result doesn't contain today's date, you won't get the same error again and the DropDownList won't select any of its items.