Hi i have Attendance and Departure System on mvc Using Ado.Net My Connection Name is (DBConnection) i have Two Method One For OnClick TimeIn and AND OTHER one for TimeOut , My DataBase Name LoginTime and My Table is Attendance I have Problem in onclick timein Btton check if row not exist in my Attendance table insert new row else show Message "You Already TimeIn"
public void Addtime(Attendance AddTim)
{
SqlCommand comm = new SqlCommand("select * from Attendance where UserID=#user", conn);
comm.Parameters.AddWithValue("#user", AddTim.UserID);
conn.Open();
var rd = comm.ExecuteReader();
bool sat = rd.Read();
conn.Close();
if (sat == true)
{
SqlCommand updCommand = new SqlCommand("UPDATE Attendance SET TimeIn=#timein WHERE UserID=#userid", conn);
updCommand.Parameters.AddWithValue("#userid", AddTim.UserID);
updCommand.Parameters.AddWithValue("#timein", DateTime.Now);
conn.Open();
int rowsUpdated = updCommand.ExecuteNonQuery();
var rdr = comm.ExecuteReader();
conn.Close();
}
else
{
SqlCommand insCommand = new SqlCommand("INSERT into Attendance (UserID,TimeIn) VALUES (#userid,#timein)", conn);
insCommand.Parameters.AddWithValue("#userid", AddTim.UserID);
insCommand.Parameters.AddWithValue("#timein", DateTime.Now);
conn.Open();
int rowsUpdated = insCommand.ExecuteNonQuery();
var rdr = comm.ExecuteReader();
conn.Close();
}
}
public void Addtimout(Attendance addtimout)
{
SqlCommand UpDCommand = new SqlCommand("UPDATE Attendance SET TimeOut=#timeout WHERE UserID=#userid", conn);
UpDCommand.Parameters.AddWithValue("#UserID", addtimout.UserID);
UpDCommand.Parameters.AddWithValue("#timeout", DateTime.Now);
conn.Open();
UpDCommand.ExecuteNonQuery();
conn.Close();
}
}
}
There is probably more going on then what I can deduce from your question and no real explanation of the error (if any) you are getting. If this is so please post the error or unexpected behavior, and the database schema would also be helpful
I did notice that you are doing multiple insert or update statements in that block, as you are executing each query twice; once as a NonQuery and again as a Reader.
int rowsUpdated = insCommand.ExecuteNonQuery();
var rdr = comm.ExecuteReader();
The original query to check doesn't look to great to me. If you simply want to check for a row count, you could use SELECT Count(*), and execute via ExecuteScalar(). This will remove the overhead of a Reader
public void Addtime(Attendance AddTim) {
SqlCommand comm = new SqlCommand("select Count(*) from Attendance where UserID=#user", conn);
comm.Parameters.AddWithValue("#user", AddTim.UserID);
conn.Open();
int uc = (int)comm.ExecuteScalar();
bool sat = (uc > 0);
conn.Close();
Related
I have a DropDownList that gets populated by a SQL Server table called tblVisa. My issue is that the values that are being populated from the SQL Server table are not being saved. Everything else gets saved except for my DropDownLists. I've tried using .SelectedValue and .Text, but it still does not work.
Here is my code
protected void PopulateVisaType()
{
List<ListItem> result = new List<ListItem> { new ListItem("", "") };
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "SELECT VisaType FROM tblVisa ORDER BY VisaType ASC" };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
result.Add(new ListItem(read["VisaType"].ToString(), read["VisaType"].ToString()));
}
read.Close();
sqlConn.Close();
cmd.Dispose();
DDLVisa.DataSource = result;
DDLVisa.DataValueField = "value";
DDLVisa.DataTextField = "text";
DDLVisa.DataBind();
}
Here's my code for saving the information into the database:
protected void LbSaveProfile_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "spSaveNewProviderInformation", CommandType = CommandType.StoredProcedure };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
cmd.Parameters.AddWithValue("#EmployeeNumber", TbEmployeeNumber.Text.Trim());
cmd.Parameters.AddWithValue("#SSN", TbSSN.Text.Trim());
cmd.Parameters.AddWithValue("#ContractType", DDLContractType.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Firstname", TbFirstname.Text.Trim());
cmd.Parameters.AddWithValue("#Lastname", TbLastname.Text.Trim());
cmd.Parameters.AddWithValue("#MiddleInitial", TbMiddleInitial.Text.Trim());
cmd.Parameters.AddWithValue("#ContractRenewalDate", TbContractRenewalDate.Text.Trim());
cmd.Parameters.AddWithValue("#Position", DDLPosition.Text.Trim());
cmd.Parameters.AddWithValue("#Specialty", DDLSpecialty.Text.Trim());
cmd.Parameters.AddWithValue("#PrimaryDepartment", DDLPrimaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#SecondaryDepartment", DDLSecondaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#Gender", DDLGender.Text.Trim());
cmd.Parameters.AddWithValue("#Birthdate", TbBirthdate.Text.Trim());
cmd.Parameters.AddWithValue("#EmailAddress", TbEmailAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PhoneNumber", TbPhoneNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Address", TbAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PassportNumber", TbPassportNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Citizenship", DDLCitizenship.Text.Trim());
cmd.Parameters.AddWithValue("#Visa", DDLVisa.Text.Trim());
cmd.Parameters.AddWithValue("#Status", 1);
cmd.ExecuteNonQuery();
sqlConn.Close();
Alert("Provider Information saved!");
ClearControls();
}
You much better to provide the drop down list with column names.
So, say this:
protected void PopulateVisaType()
{
SqlConnection sqlConn = new SqlConnection("");
using (SqlCommand cmd = new SqlCommand("SELECT VisaType FROM tblVisa ORDER BY VisaType ASC", sqlConn))
{
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
DDLVisa.DataSource = cmd.ExecuteReader();
DDLVisa.DataValueField = "VisaType";
DDLVisa.DataTextField = "VisaType";
DDLVisa.DataBind();
//DDLVisa.Items.Insert(0, new ListItem("")); // optional blank row choice
sqlConn.Close();
}
}
So the TextField, and the DataText field need to be a named column from the data source.
I also included an optional first blank option if you need/want/expect to have no choice.
However, keep in mind that this empty string should be translated into a null in your database if you don't allow (or want) empty strings, and want a null for that value. This applies to all of your values. (perhaps the stored procedure does this?).
I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.
I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();
I am fetching records of users and binding it to gridview. I want to show the number of results returned like "15 results found". I used RecordsAffected but I think it wont work with select statement. Any alternate way?
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name, city, number where age between " + from.Text + "AND " + to.Text;
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
reader.Close();
usersgrid.DataSource = cmd.ExecuteReader();
usersgrid.DataBind();
con.Close();
}
else
{
result.Visible = true;
}
}
}
Now I want to show number of rows returned on a label.
int affectedRows = cmd.ExecuteNonQuery();
that would work for you insted of cmd.ExecuteReader();
another alternative will be to get rowcount of the usersGrid control
int Count = usersGrid.Rows.Count-((usersGrid.PageCount-1) * usersGrid.PageSize);
I have question about using why i can not use the same instance of SQLCommand more than one time in the same code?
I tried the code down here and it runs good for the gridview but when i changed the query by using cmd.CommandText() method it keeps saying:
There is already an open DataReader associated with this Command which must be closed first.
This is the code:
string cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Select top 10 FirstName, LastName, Address, City, State from Customers";
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
finally
{
con.Close();
}
The problem is that you are using the SqlCommand object to generate a DataReader via the command.ExecuteReader() command. While that is open, you can't re-use the command.
This should work:
using (var reader = cmd.ExecuteReader())
{
GridView1.DataSource = reader;
GridView1.DataBind();
}
//now the DataReader is closed/disposed and can re-use command
cmd.CommandText = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
There is already an open DataReader associated with this Command which must be closed first.
This is the very reason you don't share a command. Somewhere in your code you did this:
cmd.ExecuteReader();
but you didn't leverage the using statement around the command because you wanted to share it. You can't do that. See, ExecuteReader leaves a connection to the server open while you read one row at a time; however that command is locked now because it's stateful at this point. The proper approach, always, is this:
using (SqlConnection c = new SqlConnection(cString))
{
using (SqlCommand cmd = new SqlCommand(sql, c))
{
// inside of here you can use ExecuteReader
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// use the reader
}
}
}
These are unmanaged resources and need to be handled with care. That's why wrapping them with the using is imperative.
Do not share these objects. Build them, open them, use them, and dispose them.
By leveraging the using you will never have to worry about getting these objects closed and disposed.
Your code, written a little differently:
var cs = ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
var gridSql = "Select top 10 FirstName, LastName, Address, City, State from Customers";
var cntSql = "SELECT TOP 10 COUNT(CreditLimit) FROM Customers";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand(gridSql, con))
{
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
using (SqlCommand cmd = new SqlCommand(cntSql, con))
{
int total = (int)cmd.ExecuteScalar();
TotalCreditLble.Text = "The total Credit :" + total.ToString();
}
}
catch(Exception exp)
{
Response.Write(exp.Message);
}
}
Thank u quys but for the guys who where talking about using block !
why this code work fine which i seen it on example on a video ! It's the same thing using the same instance of SqlCommand and passing diffrent queries by using the method CommanText with the same instance of SqlCommand and it's execute just fine , this is the code :
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "Delete from tbleProduct where ProductID= 4";
int TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "Insert into tbleProduct values (4, 'Calculator', 100, 230)";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
cmd.CommandText = "ypdate tbleProduct set QtyAvailbe = 234 where ProductID = 2";
TotalRowsAffected = cmd.ExecuteNonQuery();
Response.Write("Total rows affected :" + TotalRowsAffected );
}