I am getting error on updating database in C#. Here is the code:
string connectionstring = "server=AMAN;database=student;Integrated Security=True";
SqlConnection conn;
string Admission_no = txtAddmissionNo.Text;
SqlCommand cmd;
conn = new SqlConnection(connectionstring);
conn.Open();
string query = "update fees set prospectues_fee=#prospectues_fee, registration_fee=#registration_fee,admission_fee=#admission_fee ,security_money=#security_money,misslaneous_fee=#misslaneous_fee,development_fee=#development_fee,transport_fair=#transport_fair,computer_fee=#computer_fee ,activity=#activity,hostel_fee=#hostel_fee,dely_fine=#dely_fine,back_dues=#back_dues,tution_feemonth=#tution_feemonth ,tution_fee=#tution_fee,other_fee=#other_fee,total=#total,deposit=#deposit,dues=#dues where Admission_no=#Admission_no";
cmd=new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("#Admission_no", Admission_no);
cmd.Parameters.AddWithValue("#prospectues_fee", prospectues_fee);
cmd.Parameters.AddWithValue("#registration_fee", registration_fee);
cmd.Parameters.AddWithValue("#admission_fee", admission_fee);
cmd.Parameters.AddWithValue("#security_money", security_money);
cmd.Parameters.AddWithValue("#misslaneous_fee", misslaneous_fee);
cmd.Parameters.AddWithValue("#development_fee", development_fee);
cmd.Parameters.AddWithValue("#transport_fair", transport_fair);
cmd.Parameters.AddWithValue("#computer_fee", computer_fee);
cmd.Parameters.AddWithValue("#activity", activity);
cmd.Parameters.AddWithValue("#hostel_fee", hostel_fee);
cmd.Parameters.AddWithValue("#dely_fine", dely_fine);
cmd.Parameters.AddWithValue("#back_dues", back_dues);
cmd.Parameters.AddWithValue("#tution_fee", tution_fee);
cmd.Parameters.AddWithValue("#other_fee", other_fee);
cmd.Parameters.AddWithValue("#total", total);
cmd.Parameters.AddWithValue("#tution_feemonth", tution_feemonth);
cmd.Parameters.AddWithValue("#deposit", deposit_fee);
cmd.Parameters.AddWithValue("#dues", dues);
cmd = new SqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Error is #prospectues_fee scalar must be declared, which I have already declared.
The error is simpler than I thought:
cmd = new SqlCommand(query, conn);
... // lots of code
cmd = new SqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
You are creating a second command just prior to executing it; this second command has the text but no parameters. Remove this second new SqlCommand line.
This sounds like the dreaded null vs DBNull issue. null in a parameter means "don't send this". Which is really really silly, but there we are. Try with:
cmd.Parameters.AddWithValue("#prospectues_fee",
((object)prospectues_fee) ?? DBNull.Value);
now repeat for all of the parameters... or just add a method that loops over them and checks them:
static void FixTheCrazy(DbCommand command) {
foreach(DbParameter param in command.Parameters) {
if(param.Value == null) param.Value = DBNull.Value;
}
}
Alternatively, use a tool like dapper that will do it for you:
using(varconn = new SqlConnection(connectionstring))
{
conn.Execute(query, new {
Admission_no, prospectues_fee, registration_fee, ...
deposit_fee, dues });
}
Related
In the project I call a method to query additional information with a SqlConnection block, but then I validate if exists in a second table using another sqlconnection block, but it is supposed to be disposed (closed) after getting back to the method InsertNewData, but when calling to Open the connection for the Insert, I'm getting the following message:
The connection was not closed. The connection's current state is open.
My code is like this:
public void InsertNewData(string operation)
{
DataTable dt = new DataTable();
try
{
if (operation!= string.Empty)
{
using (SqlConnection oconn = new SqlConnection(myDBone))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string query = "SELECT * FROM operations "+
"WHERE idoper=#id";
oconn.Open();
cmd = new SqlCommand(query, oconn);
cmd.Parameters.Add(new SqlParameter("#id", operation.ToString()));
da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
if (dt.Rows.Count > 0)
{
using (SqlConnection con = new SqlConnection(myDBtwo))
{
SqlCommand com = new SqlCommand();
string query= "";
foreach (DataRow x in dt.Rows)
{
if (ValidateData(x) == false)
{
query= "INSERT INTO history(iddata,description, datehist ) "+
" VALUES(#id,#descrip,GETDATE())";
con.Open(); //Here throws the Exception error
com = new SqlCommand(query, con);
com.Parameters.Add(new SqlParameter("#id", x["idoper"].ToString()));
com.Parameters.Add(new SqlParameter("#descrip", x["description"] ));
com.ExecuteNonQuery();
}
}
}
}
}
}
catch (Exception x)
{
throw x;
}
}
public bool ValidateData(DataRow row)
{
bool exists= false;
string operation= row["idoper"].ToString();
string descrip= row["description"].ToString();
if (operation!= string.Empty && descrip!= string.Empty)
{
using (SqlConnection oconn = new SqlConnection(sqlrastreo))
{
SqlCommand cmd = new SqlCommand();
string query = "SELECT COUNT(*) FROM history "+
"WHERE iddata=#id AND description=#descrip";
oconn.Open();
cmd = new SqlCommand(query, oconn);
com.Parameters.Add(new SqlParameter("#id", operation));
com.Parameters.Add(new SqlParameter("#descrip", descrip));
int count = (int) cmd.ExecuteScalar();
if (count > 0)
exists= true;
}// Here it should be Disposed or closed the SqlConnection
}
return exists;
}
What I'm doing wrong, because it's suppose to be closed the other connection and the other hasn't been opened ? or Should I Still call the Close() method for each SqlConnection inside the block Using?
Updated:
I've changed to parameters for best reading code and recommendation syntax.
NOTE
The values and parameters aren't the real ones, my real table descriptions have about 8 fields, but I validate with just two parameters that aren't primary key, but considering that I can't edit the table properties (Have only reading permissions for that database).
Update 2:
Thanks to the recommendation of Sean Lange, it was better and so simple to use a Store Procedure (SP) to validate and insert at the same time, so I do it as follow in code of the process:
public void InsertNewData(string operation)
{
try
{
if(operation == string.Empty)
return;
using(SqlConnection con = new SqlConnection(myDBtwo))
{
con.Open();
var cmd = new SqlCommand("SP_InsertData", con);
cmd.Parameters.Add(new SqlParameter("#id", operation));
cmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{ throw ex; }
}
And then in my SP I insert a select statement of the parameter, to avoid duplicates and also do it in One go:
CREATE PROCEDURE SP_InsertData #id VARCHAR(10)
AS
BEGIN
INSERT INTO History
SELECT O.idoper, O.description
FROM myDBone.dbo.operations O
LEFT JOIN History H
ON H.iddata = O.idoper AND H.description = O.description
WHERE O.idoper=#id AND H.iddata IS NULL
END
Thanks for your support, and hope it helps someone.
First your code is badly written,as they have suggested you don't need to validate,try catch will do it for you.second opening a connection inside a loop ( foreach in your case) will will result to trying to open already open connection. Example here you could do something like
query= "INSERT INTO history(iddata,description, datehist" VALUES(#id,#descrip,GETDATE())";
using (SqlConnection con = new SqlConnection(myDBtwo))
{
con.Open();
SqlCommand com = new SqlCommand(query,con);
foreach (DataRow x in dt.Rows)
{
com.Parameters.Add(new SqlParameter("#id", x["idoper"].ToString()));
com.Parameters.Add(new SqlParameter("#descrip", x["description"] ));
com.ExecuteNonQuery();
}
}
}
I,m designing a CMS(campus Management System) and i wana delete some record...but its neither working nor generate any error...just return zero in "result " varaiable mentioned in code
public void DeleteAnnouncement(BusinessObject bo)
{
string ConnStr = Connection();
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
string query = "Delete from Anouncement where AnnouncementID=#i";
SqlCommand cmd = new SqlCommand(query, conn);
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine("\t============================================\n\n");
}
}
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
You're missing "#" in front of parameter name.
Correct: SqlParameter p1 = new SqlParameter("#i", bo.A_ID);
Your code works and deletes a record from Anouncement table, if AnnouncementID matches with the value of bo.A_ID, if value of bo.A_ID doesn't match with AnnouncementID, cmd.ExecuteNonQuery(); returns 0. If it's not deleting that means AnnouncementID doesn't match with the value of bo.A_ID.
But I suggest improve you code through using statement, this using statement ensures that Dispose is called even if an exception occurs while methods on the object are called.
string ConnStr = Connection();
string query = "Delete from Anouncement where AnnouncementID=#i";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
try
{
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine
("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine
("\t============================================\n\n");
}
}
catch (Exception ex)
{
//Do your exception handling work
}
}
}
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}
First question:
Say I have
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
Does the connection get closed? Because technically we never get to the last } as we return before it.
Second question:
This time I have:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
}
catch (Exception) { /*Handle error*/ }
Now, say somewhere in the try we get an error and it gets caught. Does the connection still get closed? Because again, we skip the rest of the code in the try and go directly to the catch statement.
Am I thinking too linearly in how using works? ie Does Dispose() simply get called when we leave the using scope?
Yes
Yes.
Either way, when the using block is exited (either by successful completion or by error) it is closed.
Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
try
{
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
catch (Exception)
{
/*Handle error*/
}
}
Yes to both questions. The using statement gets compiled into a try/finally block
using (SqlConnection connection = new SqlConnection(connectionString))
{
}
is the same as
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
}
finally
{
if(connection != null)
((IDisposable)connection).Dispose();
}
Edit: Fixing the cast to Disposable
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Here is my Template. Everything you need to select data from an SQL server. Connection is closed and disposed and errors in connection and execution are caught.
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CompanyServer"].ConnectionString;
string selectStatement = #"
SELECT TOP 1 Person
FROM CorporateOffice
WHERE HeadUpAss = 1 AND Title LIKE 'C-Level%'
ORDER BY IntelligenceQuotient DESC
";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand(selectStatement, conn))
{
try
{
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
Console.WriteLine(dr["Person"].ToString());
}
}
else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
}
}
catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
if (conn.State == System.Data.ConnectionState.Open) conn.Close();
}
}
* Revised: 2015-11-09 *
As suggested by NickG; If too many braces are annoying you, format like this...
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand(selectStatement, conn))
{
try
{
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
if (dr.HasRows)
while (dr.Read()) Console.WriteLine(dr["Person"].ToString());
else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
}
catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
if (conn.State == System.Data.ConnectionState.Open) conn.Close();
}
Then again, if you work for EA or DayBreak games, you can just forgo any line-breaks as well because those are just for people who have to come back and look at your code later and who really cares? Am I right? I mean 1 line instead of 23 means I'm a better programmer, right?
using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand comm = new SqlCommand(selectStatement, conn)) { try { conn.Open(); using (SqlDataReader dr = comm.ExecuteReader()) if (dr.HasRows) while (dr.Read()) Console.WriteLine(dr["Person"].ToString()); else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)"); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } if (conn.State == System.Data.ConnectionState.Open) conn.Close(); }
Phew... OK. I got that out of my system and am done amusing myself for a while. Carry on.
Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.
From MSDN:
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
Using generates a try / finally around the object being allocated and calls Dispose() for you.
It saves you the hassle of manually creating the try / finally block and calling Dispose()
In your first example, the C# compiler will actually translate the using statement to the following:
SqlConnection connection = new SqlConnection(connectionString));
try
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
finally
{
connection.Dispose();
}
Finally statements will always get called before a function returns and so the connection will be always closed/disposed.
So, in your second example the code will be compiled to the following:
try
{
try
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
finally
{
connection.Dispose();
}
}
catch (Exception)
{
}
The exception will be caught in the finally statement and the connection closed. The exception will not be seen by the outer catch clause.
I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.
try
{
using (var con = new SqlConnection(#"Data Source=..."))
{
var cad = "INSERT INTO table VALUES (#r1,#r2,#r3)";
using (var insertCommand = new SqlCommand(cad, con))
{
insertCommand.Parameters.AddWithValue("#r1", atxt);
insertCommand.Parameters.AddWithValue("#r2", btxt);
insertCommand.Parameters.AddWithValue("#r3", ctxt);
con.Open();
insertCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
No matter where's the try/catch placed, the exception will be caught without issues.
Old thread but still relevant. I arrived here looking for a way out of having a using statement inside of a using statement. I am happy with this, notwithstanding any future insightful comments that change my mind. ;) Conversations here helped. Thanks. Simplified for readability -
public DataTable GetExchangeRates()
{
DataTable dt = new DataTable();
try
{
logger.LogInformation($"Log a message.");
string conStr = _config.GetConnectionString("conStr");
using (SqlCommand cmd = new SqlCommand("someProc", new SqlConnection(conStr)))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
dt.Load(cmd.ExecuteReader());
}
return dt;
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
}
}
I am new to ADO.net. I actually created a sample database and a sample stored procedure. I am very new to this concept. I am not sure of how to make the connection to the database from a C# windows application. Please guide me with some help or sample to do the same.
Something like this... (assuming you'll be passing in a Person object)
public int Insert(Person person)
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand dCmd = new SqlCommand("InsertData", conn);
dCmd.CommandType = CommandType.StoredProcedure;
try
{
dCmd.Parameters.AddWithValue("#firstName", person.FirstName);
dCmd.Parameters.AddWithValue("#lastName", person.LastName);
dCmd.Parameters.AddWithValue("#age", person.Age);
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
It sounds like you are looking for a tutorial on ADO.NET.
Here is one about straight ADO.NET.
Here is another one about LINQ to SQL.
This is the usual pattern (it might be a bit different for different databases, Sql Server does not require you to specify the parameters in the command text, but Oracle does, and in Oracle, parameters are prefixed with : not with #)
using(var command = yourConnection.CreateCommand())
{
command.CommandText = "YOUR_SP_CALL(#PAR1, #PAR2)";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#PAR1", "lol"));
command.Parameters.Add(new OdbcParameter("#PAR2", 1337));
command.ExecuteNonQuery();
}
Something like this:
var connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
var conn = new SqlConnection(connectionString);
var comm = new SqlCommand("YourStoredProc", conn) { CommandType = CommandType.StoredProcedure };
try
{
conn.Open();
// Create variables to match up with session variables
var CloseSchoolID = Session["sessCloseSchoolID"];
// SqlParameter for each parameter in the stored procedure YourStoredProc
var prmClosedDate = new SqlParameter("#prmClosedDate", closedDate);
var prmSchoolID = new SqlParameter("#prmSchoolID", CloseSchoolID);
// Pass the param values to YourStoredProc
comm.Parameters.Add(prmClosedDate);
comm.Parameters.Add(prmSchoolID);
comm.ExecuteNonQuery();
}
catch (SqlException sqlex)
{
}
finally
{
conn.Close();
}
If using SQL Server:
SqlConnection connection = new SqlCOnnection("Data Source=yourserver;Initial Catalog=yourdb;user id=youruser;passowrd=yourpassword");
SqlCommand cmd = new SqlCommand("StoredProcName", connection);
cmd.CommandType=StoredProcedureType.Command;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
If not then replace Sql with Ole and change the connection string.
Here is a good starting point http://support.microsoft.com/kb/310130
OdbcConnection cn;
OdbcCommand cmd;
OdbcParameter prm;
OdbcDataReader dr;
try {
//Change the connection string to use your SQL Server.
cn = new OdbcConnection("Driver={SQL Server};Server=servername;Database=Northwind;Trusted_Connection=Yes");
//Use ODBC call syntax.
cmd = new OdbcCommand("{call CustOrderHist (?)}", cn);
prm = cmd.Parameters.Add("#CustomerID", OdbcType.Char, 5);
prm.Value = "ALFKI";
cn.Open();
dr = cmd.ExecuteReader();
//List each product.
while (dr.Read())
Console.WriteLine(dr.GetString(0));
//Clean up.
dr.Close();
cn.Close();
}
catch (OdbcException o) {
MessageBox.Show(o.Message.ToString());
}