Standard for database connection - try/catch? - c#

I am new to coding in Visual Studio and C#. I have my connection to my db working, and I can insert/update/delete just fine. But what if the database cannot connect one day? What kind of precautions should be coded? I think maybe a try/catch?
For example I have this code:
using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
{
sqlConn.Open();
//Insert text into db
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = System.Data.CommandType.Text;
sqlCmd.CommandText = string.Format("INSERT INTO Person(Name, Location, City, State) VALUES (#Name, #Location, #City, #State)");
sqlCmd.Parameters.Add("#EventName", SqlDbType.NVarChar, 255).Value = name;
sqlCmd.Parameters.Add("#Location", SqlDbType.NVarChar, 255).Value = location;
sqlCmd.Parameters.Add("#City", SqlDbType.NVarChar, 30).Value = city;
sqlCmd.Parameters.Add("#State", SqlDbType.NVarChar, 2).Value = state;
sqlCmd.ExecuteNonQuery();
}
}
}
Should that code be under try? What should be under the catch? Is there any other standard to catch if a database cannot connect or if some unexpected error occurs? Thank you.

Related

I want to Insert RadioButton Value in SQL Database using Classes

I created a Class name EmployeeDAta write this code here and i want to Insert Radiobutton value in SQL Database
public static void AddEmployee(Employee employee)
{
string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = employee.Name;
cmd.Parameters.Add("#FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 50).Value = employee.Address;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = employee.Email;
cmd.Parameters.Add("#Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
cmd.Parameters.Add("#Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
cmd.Parameters.AddWithValue("#VB", SqlDbType.Bit).Value = employee.VB;
cmd.Parameters.AddWithValue("#ASP", SqlDbType.Bit).Value = employee.ASP;
cmd.Parameters.AddWithValue("#Gender", SqlDbType.Int).Value = employee.Gender;
conn.Open();
cmd.ExecuteNonQuery();
}
}
add a parameter to your stored procedure call:
cmd.Parameters.AddWithValue("#ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;
In the stored procedure on the database, make sure you handle the extra parameter.

C# SQL Update CommandText and Parameters

I created a simple SQL database that has one table, tblCustomerInformation, and three columns :
FirstName,
LastName,
and Email.
I'm attempting to update it however when I run the code that I listed below the program does nothing.
It doesn't crash and give me errors it just does nothing.
I'm fairly certain that my UPDATE statement is correct. I'm not sure why this isn't working at this point.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE (FirstName = #fn)";
//cmd.Parameters.Add("#ln", SqlDbType.NVarChar);
//cmd.Parameters["#ln"].Value = txtLastName.Text;
//cmd.Parameters.Add("#em", SqlDbType.NVarChar);
//cmd.Parameters["#em"].Value = txtEmail.Text;
//cmd.Parameters.Add("#fn", SqlDbType.NVarChar);
//cmd.Parameters["#fn"].Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Use this. The arrangement of cmd.Parameters... code should not be jumbled. Base it on the arrangement in your query.
using (SqlConnection Connection = new SqlConnection(#"Data Source=EWOODWARD-PC\SQL2012; Initial Catalog=CustomerGUI; Integrated Security=True"))
{
using (SqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = "UPDATE tblCustomerInformation SET LastName = #ln, Email = #em WHERE FirstName = #fn";
cmd.Parameters.AddWithValue("#ln", txtLastName.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#fn", txtFirstName.Text);
Connection.Open();
cmd.ExecuteNonQuery();
}
}
Have encountered this kind of error once.

SQL Server CE executes the same prepared statement no matter what

I'm trying to insert some data read from XML files into my database. The problem is that it only executes one prepared statement (the first one i defined) and this causes errors.
This works:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_gestiuni ([denumire],[id_ra]) Values(#denumire,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
This does not work anymore:
conn = getConnection();
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO ra_active ([denumire],[gestiune],[utilizator],[tip_activ],[nr_invetar],[categorie_activ],[patrimoniu],[id_ra]) Values(#denumire,#gestiune,#utilizator,#tip_activ,#nr_invetar,#categorie_activ,#patrimoniu,#id_ra)";
SqlCeParameter numeParam = new SqlCeParameter("#denumire", SqlDbType.NVarChar, 100);
numeParam.Value = denumire;
cmd.Parameters.Add(numeParam);
SqlCeParameter gestiuneParam = new SqlCeParameter("#gestiune", SqlDbType.Int);
gestiuneParam.Value = gestiune;
cmd.Parameters.Add(gestiuneParam);
SqlCeParameter utilizatorParam = new SqlCeParameter("#utilizator", SqlDbType.Int);
utilizatorParam.Value = utilizator;
cmd.Parameters.Add(utilizatorParam);
SqlCeParameter nrInventarParam = new SqlCeParameter("#nr_inventar", SqlDbType.NVarChar);
nrInventarParam.Value = nrInventar;
cmd.Parameters.Add(nrInventarParam);
SqlCeParameter categorieActivParam = new SqlCeParameter("#categorie_activ", SqlDbType.NVarChar);
categorieActivParam.Value = categorieActiv;
cmd.Parameters.Add(categorieActivParam);
SqlCeParameter patrimoniuParam = new SqlCeParameter("#patrimoniu", SqlDbType.Int);
patrimoniuParam.Value = patrimoniu;
cmd.Parameters.Add(patrimoniuParam);
SqlCeParameter tipActivParam = new SqlCeParameter("#tip_activ", SqlDbType.Int);
tipActivParam.Value = tipActiv;
cmd.Parameters.Add(tipActivParam);
SqlCeParameter idRAParam = new SqlCeParameter("#id_ra", SqlDbType.Int);
idRAParam.Value = idRA;
cmd.Parameters.Add(idRAParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
I get this exception:
The column name is not valid [ Node name (if any) = ,Column name = gestiune ]
This happens because it tries to insert in the previous table (from the previous prepared statement). This is insane, I haven't found any solution to this.
What I see is the parameter #nr_inventar does not exists in your command text (you have #nr_invetar there). Also if you really need to prepare the command before executing, you should set a size for all nvarchar parameters, like you did for #denumire.

Error in setting up the connection between SQL Server and C#

What is wrong with my code? When Im setting up the connection between sql server management studio and c#, it gives me this error " ExecuteNonQuery: Connection property has not been initialized."
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString= "Database= hotel; server= Sherissa\SQLEXPRESS";
con.Open();
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)");
cmd.Parameters.AddWithValue("#TransactionId",textBox1.Text);
cmd.Parameters.AddWithValue("#GuestName", textBox2.Text);
cmd.Parameters.AddWithValue("#RoomType", textBox3.Text);
cmd.Parameters.AddWithValue("#RoomNo", textBox4.Text);
cmd.Parameters.AddWithValue("#ReservationDate", textBox5.Text);
cmd.Parameters.AddWithValue("#CheckInDate", textBox6.Text);
cmd.Parameters.AddWithValue("#CheckOutDate", textBox7.Text);
cmd.Parameters.AddWithValue("#NoOfDays", textBox8.Text);
cmd.Parameters.AddWithValue("#NoOfAdults", textBox9.Text);
cmd.Parameters.AddWithValue("#NoOfChildren", textBox10.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
}
I see several errors here.
The first error is the substance of your question. To solve that issue, you need to associate your command with a particular connection. Remember, you might be connected to several different databases at the same time. A command needs to know which connection to use.
The next error is that your Sql syntax is wrong. You are missing the required VALUES keyword.
Another problem is that you don't close the connection correctly. If an exception is thrown, the code will never make it to the con.Close(); line. If this happens often enough you will lock yourself out of your database.
Finally, a nitpick. I'm not a fan of the .AddWithValue() method, because it forces .Net to try to guess the sql datatype you're using. Sometimes it guesses wrong, and when it does the performance implications can be severe, because it can break index use on the database.
Here is code that solves all four issues:
private void button1_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection("Database= hotel; server= roger\SQLEXPRESS"))
using (var cmd = new SqlCommand("insert into CheckIn VALUES (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)", con))
{
cmd.Parameters.Add("#TransactionId", SqlDbType.Int).Value = int.Parse(textBox1.Text);
cmd.Parameters.Add("#GuestName", SqlDbType.NVarChar, 50).Value = textBox2.Text;
cmd.Parameters.Add("#RoomType", SqlDbType.NVarChar, 10).Value = textBox3.Text;
cmd.Parameters.Add("#RoomNo", SqlDbType.NChar, 4).Value = textBox4.Text;
cmd.Parameters.Add("#ReservationDate", SqlDbType.DateTime).Value = datetime.Parse(textBox5.Text);
cmd.Parameters.Add("#CheckInDate", SqlDbType.DateTime).Value = datetime.Parse(textBox6.Text);
cmd.Parameters.Add("#CheckOutDate", SqlDbType.DateTime).Value = datetime.Parse(textBox7.Text);
cmd.Parameters.Add("#NoOfDays", SqlDbType.Int).Value = int.Parse(textBox8.Text);
cmd.Parameters.Add("#NoOfAdults", SqlDbType.Int).Value = int.Parse(textBox9.Text);
cmd.Parameters.Add("#NoOfChildren", SqlDbType.Int).Value = int.Parse(textBox10.Text);
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("DATA ADDED SUCCESSFULLY!!");
}
Of course I had to guess at the datatypes to use, and in my own code I would also devote a little more effort to validating the inputs before trying to parse them.
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId, #GuestName, #RoomType, #RoomNo, #ReservationDate, #CheckInDate, #CheckOutDate, #NoOfDays, #NoOfAdults, #NoOfChildren)");`
This line should be typed as,
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId, #GuestName, #RoomType, #RoomNo, #ReservationDate, #CheckInDate, #CheckOutDate, #NoOfDays, #NoOfAdults, #NoOfChildren)", con );
You need to assign the connection to your command:
SqlCommand cmd = new SqlCommand("insert into CheckIn (#TransactionId,#GuestName,#RoomType,#RoomNo,#ReservationDate,#CheckInDate,#CheckOutDate,#NoOfDays,#NoOfAdults,#NoOfChildren)", con);

ASP.net why are these queries not executing?

In my code neither of these queries appear to be running. The debug label is printing as "end" so it is executing something inside that code block, just appears it doesn't like the queries?
// Check input is all valid
if (Page.IsValid)
{
debug.Text = "begin";
using (SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand(
"UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO tblSiteSettings (allowProductRatings, allowComments, " +
"siteName, settingDate, isActive) VALUES (#allowRatings, " +
"#allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cn.Close();
}
debug.Text = "end";
}
}
A few questions:
Why are they not executing?
In classic ASP for inserts, updates and deletes I would use con.Execute(query) as supposed to using a recordset, am I running my update statement correctly here?
Is my design of the queries good, or should I be executing them in a different manner?
The reason it's not doing anything is because you're not actually executing the queries. What you need to do is:
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblSiteSettings (allowProductRatings, allowComments, siteName, settingDate, isActive) VALUES (#allowRatings, #allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
It's the line cmd.ExecuteNoneQuery(); that you're missing. There are various different Execute methods exposed by the SqlCommand class, the most commonly used are:
ExecuteNonQuery: Executes a query and returns no result from the query (it does return the rows affected as its return value however)
ExecuteScalar: Executes a query and returns the value in the first column of the first row
ExecuteReader: Executes a query and returns the data to a SqlDataReader
Your are missing
cmd.ExecuteScalar();
You may also reuse you SqlConnection, you can open the connection right after the using (SqlConnection cn = new Sql... statement. You don't have to close the connection when the SqlConnection is in a using block, accordning to the documentation the connection is closed when you are leaving the using block.

Categories

Resources