Page Life Cycle, does db connection go in Page_Load - c#

Currently I have The following code:
void Page_Load(object sender, System.EventArgs e)
{
string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";
SqlConnection mySqlConnection = new SqlConnection(connectionString);
string procedureString = "Callin_Insert";
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = procedureString;
mySqlCommand.CommandType = CommandType.StoredProcedure;
mySqlCommand.Parameters.Add("#LVDate", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#LVTime", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#CuID", SqlDbType.Int).Value = CustID;
mySqlCommand.Parameters.Add("#Type", SqlDbType.Int).Value = Keypress;
mySqlConnection.Open();
mySqlCommand.ExecuteNonQuery();
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
mySqlConnection.Close();
}
Basically, I am opening a connection to the Database during the page_load. I am also closing that connection in page_load. Part of my problem is that the CustID & Keypress are not getting passed, because they occur later in the page life cycle. What is the best way to open the connection, get the 2 variables (when I they are entered by the user), pass them to the database, and close the connection.
Somethings I have tried is running it _OnLoad. But this didn't work either.
Any thoughts or suggestion, are greatly appreciated.

First of SqlConnection is of IDisposible interface means it is much safer to wrap your code with using statement like this.
string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";
using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
{
string procedureString = "Callin_Insert";
SqlCommand mySqlCommand = new SqlCommand(procedureString, mySqlConnection);
mySqlCommand.CommandType = CommandType.StoredProcedure;
mySqlCommand.Parameters.Add("#LVDate", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#LVTime", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#CuID", SqlDbType.Int).Value = CustID;
mySqlCommand.Parameters.Add("#Type", SqlDbType.Int).Value = Keypress;
mySqlConnection.Open();
mySqlCommand.ExecuteNonQuery();
//i have no idea what does this mean, data adapter is for filling Datasets and DataTables
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
}
Second of all i offer you to use SqlDataSourceObject control which will make much easier to work with cases like yours.
It will know how to deal with Page.IsPostBack that you haven't implemented but should, paging and other stuff you need.

Think there are a few problems here... first of all why are you running your query and then passing it to a data adapter? The data adapter will run the select command when queried.
I suggest creating a SqlDataSource on your aspx page (not code behind) and bind your control to it. Then hook up the Selecting event and in there populate your parameters. That should happen later in the page lifecycle so your parameter values will then be set.

Related

inserting data into SQL DB from C# ASP.NET

I am trying to insert values into my SQL database, the query works on the SQL side but when it comes to implement it from C# ASP.NET, it will not insert anything into the SQL database. The code is as follows:
public partial class About : Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into sanctuary(SName) values('test')", con);
cmd = new SqlCommand("insert into species(Name) values('test1')", con);
cmd = new SqlCommand("insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Your help will be much appreciated!
If you want to execute three commands together you merge the sql of the three commands in a single string separating them with a semicolon (See Batch of Sql Commands)
string cmdText = #"insert into sanctuary(SName) values('test');
insert into species(Name) values('test1');
insert into breed(SpeciesID, BreedName, FoodCost, HousingCost)
SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species";
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.ExecuteNonQuery();
The first problem in your code is that you need to execute each single command and not just the last one. Finally, if you don't see even the insert for the last command could be because your table species is empty and thus the final command has nothing to insert.
Last note, the point underlined by Zohar Peled about NOT keeping a global connection object around, is very important, follow the advice.
You only execute the last command, so there is nothing in species. Since there is nothing in species, the select returns no results so nothing gets inserted into breed.
Also, keeping an SqlConnection object on the page level is not a good idea. SQL connections should be opened right before executing queries and disposed immediately after.
A better code would look like this:
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using(var com = new SqlCommand("insert into sanctuary(SName) values('test');insert into species(Name) values('test1');insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species", con)
{
con.Open();
com.ExecuteNonQuery();
}
}
You can, of course, execute each SQL statement separately (though in this case it's not the best course of action since it means 3 round trips to the database instead of just one):
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using(var com = new SqlCommand("insert into sanctuary(SName) values('test');", con)
{
con.Open();
com.ExecuteNonQuery();
com.CommandText = "insert into species(Name) values('test1');";
com.ExecuteNonQuery();
com.CommandText = "insert into breed(SpeciesID, BreedName, FoodCost, HousingCost) SELECT SpeciesID, ('breed'), ('12'), ('21') FROM species;";
com.ExecuteNonQuery();
}
}

Using sql tableadapters to update database C#

I am building an application for a group of friends and myself to use for DnD sessions. Part of the program involves taking all of the values that are entered for our characters, items, etc and storing them to a database. I have the database built, and am pulling from the database into the program, however I am unable to return data to the database. I have the data coming into a dataset, and all of my edits are affecting the dataset, but I cannot get anything to affect the actual source database tables.
Below I have the button that I intend to use to update items in the characters' packs. I have both dataadapter, and tableadapter methods included that I have tried.
private void btnaddpack_Click(object sender, EventArgs e)
{
if (txtbxpack.Text != "")
{
/*connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName)" + "WHERE Id = '" + this.lstpack.SelectedValue + "';";
cmd.ExecuteNonQuery();
cmd.Clone();*/
string packitem = txtbxpack.Text; //will take item from an textbox
this.packTableAdapter.Insert(packitem);
this.Validate();
this.packBindingSource.EndEdit();
this.packTableAdapter.Update(this.dnD_MachineDataSet.Pack);
}
PopulatePack();
Here is my populate code in case someone needs that:
private void PopulatePack()
{
using (connection = new SqlConnection(connectionString)) //this is all about opening the connection to the sqldatabase, normally it would need to be closed, but this uses idisposable, so it will close itself
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Pack", connection))
{
DataTable packtable = new DataTable();
adapter.Fill(packtable);
lstpack.DataSource = packtable;
lstpack.DisplayMember = "Item";
lstpack.ValueMember = "Id";
}
}
As mentioned above, all of the changes are appearing whenever I re-populate the listboxes that draw upon the dataset, hence why this is an issue of trying to get that data back into the source database. I will make the obligatory "I'm relatively new to using databases" statement as it will do no good to pretend that I am an expert.
Thanks.
In the commented code, you would need to do the following:
assign the connection object to the SqlCommand object's Connection
property
pass the item name to your #ItemName parameter
assign a parameter value to the 'Id' column in the WHERE clause
remove, 'cmd.Clone();', and replace with, 'connection.Close();'
Here is what the code should look like:
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName) WHERE Id = #ID;";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ItemName", txtbxpack.Text);
cmd.Parameters.AddWithValue("#ID", this.lstpack.SelectedValue);
cmd.ExecuteNonQuery();
connection.Close();

Updating OLEDB Database using UPDATE Query

I've Edited this question to prevent asking another. I'm trying to update a datatable in MS Access using an UPDATE query and Parameters. The code doesn't give an error and runs fine, but it does't save the updated data and I can't work out why.
Here's the code I'm using :
if (Editing)
{
string Query = "UPDATE [Employee] SET PayrollNo=#PayrollNo, FirstName=#FirstName, LastName=#LastName, AnnualHolidayEntitlement=#AnnualHolidayEntitlement, DaysTakenToDate=#DaysTakenToDate WHERE PayrollNo = #SentPayroll";
string ConnString = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
using (OleDbConnection conn = new OleDbConnection(ConnString))
using (OleDbCommand UpdateEmployee = new OleDbCommand(Query, conn))
{
conn.Open();
UpdateEmployee.Parameters.AddWithValue("#SentPayroll", OleDbType.Integer).Value = Convert.ToInt32(PassPayrollNo);
UpdateEmployee.Parameters.AddWithValue("#PayrollNo", OleDbType.Integer).Value = Convert.ToInt32(TxtPayrollNo.Text);
UpdateEmployee.Parameters.AddWithValue("#FirstName", OleDbType.VarChar).Value = TxtFirstName.Text;
UpdateEmployee.Parameters.AddWithValue("#LastName", OleDbType.VarChar).Value = TxtLastName.Text;
UpdateEmployee.Parameters.AddWithValue("#AnnualHolidayEntitlement", OleDbType.Integer).Value = Convert.ToInt32(TxtAHE.Text);
UpdateEmployee.Parameters.AddWithValue("#DaysTakenToDate", OleDbType.Integer).Value = Convert.ToInt32(TxtDTTD.Text);
UpdateEmployee.ExecuteScalar();
BtnSubmit.Enabled = false;
MessageBox.Show("Data Edited Successfully");
}
How can I change this code so that it works? Thanks in advance.
EDIT/ANSWER.
I didn't know and chances are if you're having problems with an UPDATE query you may not know it either. When adding parameters you need to add them in the same order they are called in the query. In my code the first parameter should be added last, since it is last in the stringQuery. I moved it and it worked fine!
Why does invoking my UPDATE query in an Access database via OleDb not work?
If anyone else has this issue with UPDATE queries, It took me too long to find this question, where someone clears it up great.

conversion failed varchar to int

Below is the code for combo box selected value change. It is supposed to pick up a value from DB and display it in a text box.
protected void cmbPujaName_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con2 = null;
con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SRKBSDB"].ConnectionString);
SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName =" + cmbPujaName.SelectedValue, con2);
DataSet pamtds = new DataSet();
pamt.Fill(pamtds); ......... Error shown here...........
txtAmount.Text = pamtds.Tables[0].Rows[0]["Amount"].ToString();
}
You're missing quotes but... do not do that like this. This way is like leaving your door wide open and invite thieves inside for a tea party. Or SQL Injection attack, inviting hackers to steal your whole database and/or server and take full control over it.
Have such code instead:
SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName = #name", con2);
pamt.SelectCommand.Parameters.AddWithValue("#name", cmbPujaName.SelectedValue);
DataSet pamtds = new DataSet();
pamt.Fill(pamtds);
This way you won't have to mess around with quotes, plus you're better protected against hackers.
It's a better practice to write a query using SqlCommand parameters by mentioning proper datatype to avoid sql injection attacks. Try to handle null values as well.
SqlDataAdapter pamt = new SqlDataAdapter("select Isnull(Amount,0.0) Amount from PoojaDietyMaster where PoojaName = #name", con2);
pamt.SelectCommand.Parameters.Add("#name",SqlDbType.VarChar).Value = cmbPujaName.SelectedValue.tostring();
DataSet pamtds = new DataSet();
pamt.Fill(pamtds);

Inserting data into sql server fails with no reason

I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)

Categories