C# update query - c#

I am finding error of No value given for one or required parameter C# update query where ever i try to update my c# access data base here is the code...
hope somebody will be of my assistant..
private void updatebutton_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string query = "update Emplyeedata set [ID]='" + midbox.Text + "',[Name]='" + mnamebox.Text + "',[Deisgnation]='" + mdesbox.Text + "',[Leave]='" + mleavebox.Text + "'Where [Name]='"+mnamebox.Text+"'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
cb();
MessageBox.Show("Updated", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

as a bit more improvement you can try like this, and if you can post the full error information.
private void updatebutton_Click()
{
using (OleDbConnection con = new OleDbConnection("Define your Connection String here"))
{
string query = #"UPDATE Emplyeedata
SET [id] = #ID
,[Name] = #Name
,[Deisgnation] = #Deisgnation
,[Leave] = #Leave
WHERE [Name] = #Name";
using (OleDbCommand cmd = new OleDbCommand(query, con) { CommandType = CommandType.Text })
{
cmd.Parameters.AddWithValue("#ID", midbox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
cmd.Parameters.AddWithValue("#Deisgnation", mdesbox.Text);
cmd.Parameters.AddWithValue("#Leave", mleavebox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
(this is a really unstructured way and please follow the SOLID Principle/s)

Related

C# set database to specific data that I want

I am currently trying delete my advertisement. But instead of deleting it from database I just want to set the status from 1 ( which means active ) to 0 (which means inactive). I have tried to use query UPDATE. But I do not know the format. My current code is
protected void btnDelete_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("DeleteImage", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("AdvID", Convert.ToInt32(hfContactID.Value));
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
Clear();
FillGridView();
LitMsg.Text = "Deleted Successfully";
ButSave.Enabled = true;
Image1.Visible = false;
}
and I believe that Delete query does not change my status to 0 so my update query is something like this.
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (FileImgsave.HasFile == true)
{
string imgfile = Path.GetFileName(FileImgsave.PostedFile.FileName);
//FileImgsave.SaveAs("Images/" + imgfile);
FileImgsave.SaveAs(Server.MapPath("~/Images/" + imgfile));
sqlCon.Open();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Advertisement SET Item=#item,ImgPath=#image,Name=#name Where AdvID='" + AdsTb.Text + "'";
cmd.Parameters.AddWithValue("#name", nameTb.Text);
cmd.Parameters.AddWithValue("#item", imgfile);
cmd.Parameters.AddWithValue("#image", "~/Images/" + imgfile);
cmd.ExecuteNonQuery();
sqlCon.Close();
FillGridView();
LitMsg.Text = "Update successfully!";
Clear();
}
Below is my delete query
ALTER PROC [dbo].[DeleteImage]
#AdvID int
AS
BEGIN
DELETE FROM Advertisement
WHERE AdvID = #AdvID
END
You forgot to Update the Status
cmd.CommandText = "UPDATE Advertisement SET Status=0, Item=#item,ImgPath=#image,Name=#name Where AdvID='" + AdsTb.Text + "'";
Status=0

Can you help me to show datagridview and Refresh after update?

This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?

SQL Insert Query Using C#

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 ! ");
}
}
}

C#.net Windows Application - Input data check before insert to Database

I am making a booking system.
I can't figure out the validation algorithm for a series of data before it insert to DB.
The primary key will be the booking ID which is automatic generate by the system.
I need to validate the bdate, btime and sname. (bdate=booking time, btime=booking time, and sname=staff name)
In case of the bdate, btime and sname is same as what the client input. the system will alert its duplicate as the staff already have booking on the same date and time.
Please find my insert query at below and appreciated you can point me to the right way.
private void btn_save_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
//query for duplicate
cmd.CommandText = "select count(*) from Booking where sname = #newName and bdate = #newDate and btime = #newTime";
// cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
//cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
// cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.CommandText = "insert into Booking(cname, bdate, btime, ccontact, sname) Values('" + txt_cname.Text + "','" + dtp_bdate.Value.Date + "','" + dtp_btime.Value.ToString("hh:mm tt") + "','" + txt_ccontact.Text + "','" + txt_sname.Text + "')";
cmd.Connection = myCon;
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
if (recordCount>0)
{
// handle duplicates
MessageBox.Show("Duplicated", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
// cmd.Connection = myCon;
//myCon.Open();
//cmd.ExecuteNonQuery();
//myCon.Close();
//MessageBox.Show(dtp_bdate.Value.ToString());
//MessageBox.Show("Booking completed", "My Application",
// MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
private bool RecordExists(string name, DateTime date, string time)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
//query for duplicate
cmd.CommandText = "select count(*) from Booking where sname = #newName and bdate = #newDate and btime = #newTime";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
return recordCount > 0;
}
private void btn_save_Click(object sender, EventArgs e)
{
if (RecordExists(txt_cname.Text, dtp_bdate.Value.Date, dtp_btime.Value.ToString("hh:mm tt"))
{
MessageBox.Show("Duplicated", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
return;
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Booking(cname, bdate, btime, ccontact, sname) Values(#newName, #newDate, #newTime, #newContact, #newSName)";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.Parameters.Add("#newContact", OleDbType.VarChar).Value = txt_ccontact.Text;
cmd.Parameters.Add("#newSName", OleDbType.VarChar).Value = txt_sname.Text;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
MessageBox.Show(dtp_bdate.Value.ToString());
MessageBox.Show("Booking completed", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
you'll need to check if the booking exists before performing your insert, so you need to add an additional step:
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from booking where cname = #newName and bdate = #newDate and ctime = #newTime";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.Connection = myCon;
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
if (recordCount>0)
{
// handle duplicates
}
when you execute this, it will either return the number of matching rows, if this is 1 or more, then you should then invoke your duplicate logic.
edited to correct code
To check if there's existing field you can make a Select and then compare:
bool InfoRepeated()
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("SELECT cname FROM yourTable;");
cmd.Connection = myCon;
myCon.Open();
try
{
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (txt_cname.Text.Equals((rdr[0].ToString())))
{
myCon.Close();
return true;
}
}
myCon.Close();
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
myCon.Close();
return false;
}
}
Let me know if it works or the error you get.
working useful code try this
BOMaster obj_data = new BOMaster();
obj_data.productid = tempid;
obj_data.categoryid =int.Parse(cmbcategory.SelectedValue.ToString());
obj_data.productcode = txtproductcode.Text;
obj_data.productname = txtproductname.Text;
obj_data.mqty = decimal.Parse(txtmqty.Text.ToString());
OleDbCommand mycmd = new OleDbCommand("select * from productmaster where productname=?", new OleDbConnection(Common.cnn));
BOMaster obj_datan = new BOMaster();
mycmd.Parameters.Add(new OleDbParameter("productname", txtproductname.Text));
mycmd.Connection.Open();
OleDbDataReader myreader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (myreader.HasRows == true)
{
// savestutus = "false";
MessageBox.Show("Product Name Already Exist", "Product", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtproductname.Focus();
return;
}
mycmd.Connection.Close();
ProductDAL obj_dal = new ProductDAL();
if (obj_dal.Save(obj_data))
{
Clear();
}

how to use sql.trans in two methods?

i have cut and paste buttons while cutting i have one sql operation and while pasting one sql operation . how to use transation statement for this .
protected void btnCut_Click(object sender, EventArgs e)
{
hidCutnode.Value = TreeView2.SelectedNode.Value;
string sqlQuery = "update CUSTOMIZEDTREE set parentid='" + 0 + "' where nodeid='" + hidCutnode.Value + "'";
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.69.200.62)(PORT=1521)))(CONNECT_DATA=(SID=orcl)));User Id=apex_demo;Password=apex_demo;";
OracleConnection con = new OracleConnection(connectionString);
con.Open();
tran = con.BeginTransaction();
OracleCommand cmd = new OracleCommand(sqlQuery, con);
cmd.Transaction = tran;
cmd.ExecuteNonQuery();
con.Close();
}
protected void btnPaste_Click(object sender, EventArgs e)
{
hidPastenode.Value = TreeView2.SelectedNode.Value;
try
{
string sqlQuery = "update CUSTOMIZEDTREE set parentid='" + hidPastenode.Value + "' where nodeid='" + hidCutnode.Value + "'";
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.69.200.62)(PORT=1521)))(CONNECT_DATA=(SID=orcl)));User Id=apex_demo;Password=apex_demo;";
OracleConnection con = new OracleConnection(connectionString);
con.Open();
OracleCommand cmd = new OracleCommand(sqlQuery, con);
tran = con.BeginTransaction();
// cmd.Connection = con;
cmd.Transaction = tran;
cmd.ExecuteNonQuery();
tran.Commit();
con.Close();
PopulateCustomTree();
}
catch (Exception ex)
{
tran.Rollback();
ex.ToString();
}
}
Pass transaction object as function parameter to the second method and dont commit in method1. Use BeginTransaction in first method only.
SqlTransaction trn = connect.BeginTransaction();
try
{
SqlCommand command = new SqlCommand(query);
command.Transaction = trn;
command.Connection = connect;
connect.Open();
command.CommandTimeout = 0;
command.ExecuteNonQuery();
trn.Commit();
}
catch (Exception ex)
{
trn.Rollback();
}
connect.Close();

Categories