I want to return the total of the values in record "hours" on the table "Courses" from my sql database I tried this code but it doesn't work:
SqlCommand cmd = new SqlCommand("Select Courses.hours from Courses inner join Sched on Courses.Id = Sched.SCourses ", con2);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses");
Label3.Text = cmd2.ToString();
}
You are not specified the connection for your sql command cmd2 .
Try this .
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses",con2);
Label3.Text = cmd2.ExexcuteScalar().ToString();
There are two problems in the code: doing while (rdr.Read()) you loop through all rows of result set and execute Select sum(hours)... as many times as many rows you get in the first query.
Depends on requirements, you might want to do if instead of while
if (rdr.Read())
Next, cmd2.ToString(); will not output the result of the query. You should either use ExecuteReader as in the first case, or use ExecuteScalar
if (rdr.Read())
{
SqlCommand cmd2 = new SqlCommand("Select sum(hours) as totalHours from Courses", con2);
Label3.Text = cmd2.ExecuteScalar().ToString();
}
Why are you totaling your hours using separate queries. Use group by clause and run only once.
SqlCommand cmd = new SqlCommand("Select Courses.id, Sum(Courses.hours) from Courses inner join Sched on Courses.Id = Sched.SCourses group by Course.id")
SqlDataReader rdr = cmd.ExecuteReader();
Label3.Text = cmd.ExecuteScalar().ToString();
Hope it will help.
Related
I want to sum all values of a column (ttl), and store result in a variable (sum), I tried some code snippets, but I didn't get any success.
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = '"+ textBox1.Text +"'",con);
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
con.Close();
}
In your code, you should close the connection after the loop, closing the connection inside the loop will cause an error:
while (dr.Read())
{
sum = Convert.ToInt32(dr[0]);
MessageBox.Show(sum.ToString());
}
con.Close();
Sum should return a single value, so you can simply get the value like this:
int sum = Convert.ToInt32(cmd1.ExecuteScalar());
Adding a variable directly to query makes it vulnerable for injections. Use parameters instead:
SqlCommand cmd1 = new SqlCommand("Select sum(ttl) from feereceipt where std_id = #id",con);
cmd1.Parameters.Add("#id", SqlDbType.VarChar).Value = textBox1.Text;
I am using this code to save hours but with the use ShowFooter property, can I enter the spaces under the columns in total how to have a use code and summaryitem format what should it be?
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO LogBook (Se,Me)VALUES(,#Se,#Me)", connection);
cmd.Parameters.AddWithValue("#Se", Convert.ToDateTime(textEdit7.Text).ToString("HH:mm"));
cmd.Parameters.AddWithValue("#Me", Convert.ToDateTime(textEdit8.Text).ToString("HH:mm"));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
After you are done inserting the data in the database , you can simply use a datareader and achieve your goal :
int totalhours;
SqlCommand cmd = new SqlCommand("Select Se,Me from LogBook",con)
SqlDataReader dr = cmd.ExecuteREader();
While (dr.Read)
{
totalhours = totalhours + Convert.ToInt32(dr[0].ToString().Split(':')(0)) + Convert.ToInt32(dr[1].ToString().Split(':')(0));
}
MessageBox.Show(totalhours);
I want to find how many rows affected when I fire a select query from C#. without insert data into dataset or datatable.
string constr = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString; //get connection string Web.config
SqlConnection con = new SqlConnection(constr);
//define Select Query
SqlCommand slct = new SqlCommand("select * From [dbo].[userdetail] where 1=1", con);
int noRows;
//open connection and execute query
con.Open();
noRows = slct.ExecuteNonQuery();
con.Close();
//define Select Query
SqlCommand select = new SqlCommand("select * From [dbo].[userdetail] where 1=0", con);
//open connection and execute query
con.Open();
noRows = select.ExecuteNonQuery();
con.Close();
First of all for your current query use ExecuteReader() and while reading the loop saying below keep a counter
int count = 0;
while(rdr.Read())
{
count++;
}
Else, use a scalar query like below and use ExecuteScalar() function
select count(*) From [dbo].[userdetail]
SqlCommand cmd = new SqlCommand("select count(*) From [dbo].[userdetail]", con);
// open connection and execute query
con.Open();
int noRows = (int)cmd.ExecuteScalar();
I'd really appreciate if someone could help me figure out how to fill two comboboxes data from two different tables. The code below doesn't seem to be working for me.
string command = "SELECT * FROM [Course]";
string command2 = "SELECT * FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
SqlDataReader reader2 = db.commandExecute(command2);
while (reader.Read())
{
comboBox2.Items.Add(reader["CourseID"].ToString());
}
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
reader.Close();
reader2.Close();
db.connectionEnd();
Instead of using two queries you can try like this
string command = "SELECT * FROM [Course] UNION ALL SELECT * FROM [Module]";
If you have columns mismatch problem while joining query use NULL as Column1 for extra column
Eg-:
string command = "SELECT CUSTID AS ID FROM [Course] UNION ALL SELECT ModuleID AS ID FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
while (reader.Read())
{
comboBox2.Items.Add(reader["ID"].ToString());
}
reader.Close();
db.connectionEnd();
Update
I thought that you are going to add two table values in same comboxbox that's why posted above code.
Can you try this code it worked for me
SqlConnection con = new SqlConnection("Data Source=pcname;Initial Catalog=database;Persist Security Info=True;User ID=sa;Password=123");
SqlCommand cmd = new SqlCommand("SELECT * FROM [Course]", con);
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [Module]", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ComboBox1.Items.Add(dr(0).ToString);
}
}
dr.Close();
SqlDataReader dr1 = cmd1.ExecuteReader;
if (dr1.HasRows)
{
while (dr1.Read)
{
ComboBox2.Items.Add(dr1(0).ToString);
}
}
dr1.close();
con.close();
Hope this help you
Change your code
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
with
while (reader2.Read())
{
// Change here the name of reader
comboBox1.Items.Add(reader2["ModuleID"].ToString());
}
I knew this is simple but I am not able to think. Displaying the count of a record from table and display it on textbox.
private void gMapControl1_Load_1(object sender, EventArgs e)
{
SqlConnection conDatabase = new SqlConnection(constring);
conDatabase.Open();
DataTable db = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(
"select count(site) from [ICPS].[dbo].[excel GPS postcode]",
conDatabase);
sda.Fill(db);
textBox29.Text = ;
SqlDataAdapter sda = new SqlDataAdapter(
"select count(site) from [ICPS].[dbo].[excel GPS postcode] "
+ "where Region = '1'",
conDatabase);
sda.Fill(db);
textBox30.Text = ;
}
You just need to use SqlCommand.ExecuteScalar instead of SqlDataAdapter like this:
SqlCommand com = new SqlCommand("select count(site) from [ICPS].[dbo].[excel GPS postcode]", conDatabase);
object count = com.ExecuteScalar();
if(count != null) textBox29.Text = count.ToString();
//The same for textBox30
More info on ExecuteScalar
Note that the code I posted is just for the idea of using ExecuteScalar, it depends on your code style when working with ADO.NET, you may want to use some using statement, or reuse your command, ... in your own way you like.
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
cmd.CommandText = "select count(site) from [ICPS].[dbo].[excel GPS postcode]";
Int32 count = (Int32) cmd.ExecuteScalar();
textBox29.Text = count.ToString();
}
When you expect just one value returned by your sql command, then use ExecuteScalar from the command object
string cmdText1 = "select count(site) from [ICPS].[dbo].[excel GPS postcode]";
using(SqlConnection conDatabase = new SqlConnection(constring))
using(SqlCommand cmd = new SqlCommand(cmdText, conDatabase))
{
conDatabase.Open();
int numRec = Convert.ToInt32(cmd.ExecuteScalar());
textBox29.Text = numRec.ToString();
}
MSDN says
Executes the query, and returns the first column of the first row in
the result set returned by the query. Additional columns or rows are
ignored
However I have noticed that you try to read the record count from two different queries.
So your code could also be written in this way to avoid a roundtrip to the database
string cmdText = "select count(site) from [ICPS].[dbo].[excel GPS postcode];" +
"select count(site) from [ICPS].[dbo].[excel GPS postcode] " +
"where Region = '1'", ;
using(SqlConnection conDatabase = new SqlConnection(constring))
using(SqlCommand cmd = new SqlCommand(cmdText, conDatabase))
{
conDatabase.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
int numRec1 = Convert.ToInt32(reader[0]);
reader.NextResult();
reader.Read();
int numRec2 = Convert.ToInt32(reader[0]);
textBox29.Text = numRec1.ToString();
textBox30.Text = numRec2.ToString();
}
}
In this way I have taken advantage of the ability of SQL Server to execute two or more commands separated by a semicolon.
To fetch a value from datatable use row[columnName]
SqlDataAdapter sda = new SqlDataAdapter(
"select count(site) As siteCount from [ICPS].[dbo].[excel GPS postcode]",
conDatabase);
sda.Fill(db);
if(db !=null && db.Rows.Count > 0)
textBox29.Text =db["siteCount"].tostring();
else
textBox29.Text ="0";
However as King King suggested here why use datatable if you have to fetch just a single row and single column use ExecuteScalar method .
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. -MSDN
SqlCommand com = new SqlCommand("select count(site) from [ICPS].[dbo].[excel GPS postcode]", conDatabase);
object siteCount = com.ExecuteScalar();
if(siteCount != null) textBox29.Text = siteCount.ToString();