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;
Related
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 1 year ago.
Improve this question
I am trying to get the row data from the database table to a label the condition is I want the highest value column to be displayed in the label with other fields currently my code is :
private void electionWinner()
{
try
{
conn.Open();
string qry = "SELECT * FROM Results WHERE (SELECT MAX(Results) FROM Results) ";
SqlCommand cmd = new SqlCommand(qry,conn);
string result = cmd.ExecuteReader().ToString();
winnerlbl.Text = result.ToString();
}
catch (SqlException es)
{
MessageBox.Show($"{es}");
}
}
}
I am currently new to c# and trying to understand it, so I am lost, thanks in advance.
The query itself isn't correct. here's why:
you did not state which column in the Results table that you want
the max of
When you adjust the select statement inside the where clause, you need to make sure your WHERE statement will either give you a true or false, currently all it does is get the max value (if you correctly add the column name)
select * from Results where COLUMNNAME= (select Max(COLUMNNAME) from Results)
Always make sure to run the query on the database before doing it inside your code
Use ORDER BY and LIMIT:
SELECT r.*
FROM Results r
ORDER BY r.Results DESC
LIMIT 1;
You can modify your query like below
`string qry = "Select ColumnName From Results where ColumnName in (SELECT Max(ColumnName) FROM Results)";`
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 3 years ago.
Improve this question
I need to show data from two different tables in mysql database in DataGridView?
When I use date from one table I do it with:
using (MySqlConnection sqlConn = new MySqlConnection(connectionString))
{
sqlConn.Open();
MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter("SELECT * FROM POSAO", sqlConn);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
dataTable.Columns.Add()
dgvPoslovi.AutoGenerateColumns = false;
dgvPoslovi.DataSource = dataTable;
}
How can I do with data from two different tables?
You should use UNION clause in your query, for simpicity sake assume you have the following 2 tables with the following column names
Table STUDENTS
columns ST_ROWID, ST_NAME, ST_PHONE
Table TEACHERS
columns TC_ROWID, TC_NAME, TC_PHONE
SELECT ST_NAME AS FULLNAME, ST_PHONE AS PHONENUMBER FROM STUDENTS
UNION
SELECT TC_NAME AS FULLNAME, TC_PHONE AS PHONENUMBER FROM TEACHERS
the above query will return all teachers and students in the same result. if you need to identify which record is student or teacher you could add a fake field to each select statement like below
SELECT ST_NAME AS FULLNAME, ST_PHONE AS PHONENUMBER, 'STUDENT' as PERSON_TYPE FROM STUDENTS
UNION
SELECT TC_NAME AS FULLNAME, TC_PHONE AS PHONENUMBER, 'TEACHER' as PERSON_TYPE FROM TEACHERS
Note that in order for the UNION to work both select statements need to have the same column names
hope this helps!
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 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 8 years ago.
Improve this question
while running the given below code, getting an error. I have to perform delete operation through gridview.
code:
protected void gvEdit_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string Emp_ID = gvEdit.DataKeys[e.RowIndex].Value.ToString();
int EId = Convert.ToInt32(Emp_ID); // error popup here
ShadingAnalysisDataSetTableAdapters.tbl_EmployeeToTeamTableAdapter tm;
tm = new ShadingAnalysisDataSetTableAdapters.tbl_EmployeeToTeamTableAdapter();
DataTable dt = new DataTable();
tm.GetDelete(EId);
BindData();
}
DB:
SQL:
DELETE FROM tbl_EmployeeToTeam WHERE (Emp_ID = #Emp_ID)
I assume that GetDelete expects a string but you're passing an int. I think so because it seems to be the parameter for Emp_ID which is a varchar. So you could simply pass that string which you already had in:
gvEdit.DataKeys[e.RowIndex].Value.ToString();
But if it's supposed to be an int, why don't you use the correct data type in the database?
Bad habits to kick : choosing the wrong data type
Update
My employee Id is strating from EMP001, EMP002..etc. So how can I use
integer data type
Why do you store always EMP at the beginning? You could also omit that and use int as type which would be more efficient and fail-safe. Then you could prepend EMP where you need to display it.
However, if you don't want to change that and Emp_ID contains only the ID without EMP you can use string concatenation:
tm.GetDelete("EMP" + Emp_ID);
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 8 years ago.
Improve this question
Is it possible to make a select query using a textbox as a reference.
Some like:
SELECT modeltype FROM txt_model.text
The value display in the textbox is the name of the table.
You could do it as described, but it is a bad idea. I suggest code like the following -- it is safe and has the same UI:
// add your table names to the list below
List<string> validTables = New List<string>() {"users", "addr", "events" };
if (validTables.IndexOf(txt_model.text.ToLower()) > 0)
{
// use "SELECT modeltype FROM "+txt_model.text to perform work
}
else
{
// error code
}
It might be that you want a dynamic list of validTables. In that case you could take the result of (with SQL Server as an example):
SELELCT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
And put it in the validTables list.
Or you could just put the result of that select in a drop down.
One way to build your query string:
string sql = string.Format("Select modeltype From {0}", txt_model.Text);
// ...
SqlCommand cmd = new SqlCommand(sql);