Alert message when certain limit has been made [closed] - c#

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.

Related

Problem to update a value in Access Database [closed]

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.

Fill data to combobox from sql command [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
I'm using below code but, it's giving me an error.
private void ma2()
{
try
{
string query = "select k7 from kholy1";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
comboBox5.Items.Add(drd.GetValue(0).ToString());
}
drd.Close();
}
catch
{
MessageBox.Show("Error ");
}
}
I'm getting an error while displaying the form!
You just simply use combo box tasks and check use Data Bound Items that's how you are able to connect it to sql database. Value member use to store it's value in database and Display Member use to Display value in front end.
You can use selected value using combobox1.SelectedValue.
Reference- Binding WPF ComboBox to a Custom List

c# to Access INSERT INTO query not working [closed]

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

How to link database with C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Okay, I am wanting to basically connect my windows form application in C# to my database, what I want it to do is display a random word from the database into the label of my form. When I say display a random word I mean display a random word from the 20 words in a table of my database. I was wondering how would you do this? I really dont want the answer as I want to learn, but could you explain how would I do this?
Thanks in advance:)
I am wanting to connect the database using Access rather than the framework provided by .NET
First of all I would like to suggest to use google first Beginners guide to connect SQL with C# then I would like you to post question regarding to one topic for instance - Connect SQL with C#. And the part with picking random word should be another solo question.
Anyway I hope this will work for you, but please, keep in mind that we are not here to code for you without any coding effort and your code.
My code:
List<string> wordList = new List<string>();
string connection = "YourConnectionString";
OleDbConnection con = new OleDbConnection(connection);
string query = "SELECT * FROM yourTable WHERE ID=#param"; // add as many conditions as you need
OleDbCommand comm = new OleDbCommand(query, con);
comm.Parameters.AddWithValue("#param", textBox1.Text); //example of parameter
con.Open();
OleDbDataReader rdr = comm.ExecuteReader();
while (rdr.Read()) //this will loop through all rows with given conditions.
{
wordList.Add(rdr.GetString(rdr.GetOrdinal("YourSQLColumn")).Trim());
}
con.Close();
Random rnd = new Random();
int randomint = rnd.Next(1, 20); // generates a random number between 1 and 20
label1.Text = wordList[randomint].ToString();
Here's a sample to get you started
public static void Main()
{
string connectionString = "data source=.\\SQLEXPRESS;Integrated Security=SSPI;database=InsertDatabaseNameHere; connection timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("select ColumnName from TableName", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
connection.Close();
}
Just set up a SQLDataReader and convert to a list...you just have a one-dimensional list of strings. You'll be looping through the results and adding them to a list. (There's probably a more elegant way to do this, but you've only got 20 strings, not 20,000, so I don't think you need to get crazy with this)
Here's another SO question to get you started...this answer is probably what you need.
You just set your Datareader up against Access (there's a bazillion hits on doing this), convert it to a list, and off you go...

Missing Rows Property in SqlDataReader [closed]

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 9 years ago.
Improve this question
public bool ValidateUser(string uName)
{
SqlCommand cmd = new SqlCommand();
if (connection == null)
{
connection = connectToDB();
}
cmd.Connection = connection;
cmd.CommandText = "Select * from Users where UserName='" + uName + "'";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
I wrote the code in my data access layer but it was giving error on rows to count the columns.
Error:
'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?)
Use HasRows instead because SqlDataReader doesn't have a property call Rows.
if (dr.HasRows)
{
return true;
}
However, if you want the count instead you may load it into a datatable
DataTable dt = new DataTable();
dt.Load(dr);
int num = dt.Rows.Count;
SqlDataReader does not have a Rows Property.
Perhaps consider the HasRows property of SqlDataReader
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.hasrows.aspx
There is no Rows property in an SqlDataReader.
But your code has many problems.
I would change your code in this way:
public bool ValidateUser(string uName)
{
using(SqlConnection cn = connectToDB())
using(SqlCommand cmd = new SqlCommand("Select count(*) from Users where UserName=#name", cn))
{
cmd.Parameters.AddWithValue("#name", uName);
return (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
}
}
The connection object is no more global and it is destroyed in
closing of the using statement.
No need to use a DataReader just to find out if the user exists or
not
Using a parameterized query to avoid SQL Injection on the input data
Avoid a global connection object. There is the connection pooling infrastructure that removes any performance problem and you are safe from excessive resource usage.
The SqlDataReader is a good choice when you need to retrieve sequentially a lot of records, but to get just the information if the user exists or not the best approach is through the ExecuteScalar method and an appropriate sql.
The parameterized query is a must for every serious database work. It will pass the work to format your input to the framework and you don't risk an Sql Injection

Categories