I was trying to use this code without transaction but it gave me error, so I want to use it with transaction. How I can use it?
My code is:
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query = "insert into users(Name, Password) values('ubaid', 'ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
SqlTransaction trans;
private void btn_Update_Click(object sender, EventArgs e)
{
try
{
con.Open();
trans = con.BeginTransaction(); // Begins transaction
string query = "insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
trans.Commit();
}
catch (Exception ex) //error occurred
{
trans.Rollback(); // Rollback transaction on error
}
}
Try the above code. Hope it helps you.
Related
Not inserting data into database and not getting any error
private void add_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(global::Employees.Properties.Settings.Default.Database1ConnectionString);
try
{
string query = "INSERT INTO Employee (username,password,city,phone)";
query += " VALUES (#username,#password,#city,#phone)";
SqlCommand myCommand = new SqlCommand(query, connection);
myCommand.Parameters.AddWithValue("#username", username.Text);
myCommand.Parameters.AddWithValue("#password", password.Text);
myCommand.Parameters.AddWithValue("#city", listBox.Text);
myCommand.Parameters.AddWithValue("#phone", phone.Text);
connection.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("Success add Employee");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally{
connection.Close();
}
}
Try this way will work as expected
string connectionString = #"data source=WS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";//Replace Your connection string
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Employee (username,password,city,phone) VALUES (#username,#password,#city,#phone)", _connection))
{
command.Parameters.AddWithValue("#username", "testuser");
command.Parameters.AddWithValue("#password", "pass");
command.Parameters.AddWithValue("#city", "TestCity");
command.Parameters.AddWithValue("#phone", "TestPhone");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Note:
Check database Name on connection string,
table name and given parameter for example #username should be same,
Make sure your syntax is correct.
Let me know if you have anymore concern.
How do i resolve ExecuteNonQuery: Connection property is not initialized. I already made my cmd.Connection = con; this is my code please help
Private void button1_Click(object sender, EventArgs e)
{
if (img_file != null)
{
FileStream fs = new FileStream(img_file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[]image = new byte[fs.Length];
fs.Read(image,0,Convert.ToString(fs.Length));
fs.Close();
SqlCommand cmd = new SqlCommand("INSERT INTO member_details (name,address,email,phone_number,picture) VALUES('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"', #pic)", con);
SqlParameter prm = new SqlParameter("#pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0,0, null, DataRowVersion.Current, image);
cmd.Parameters.Add(prm);
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
You can use below code as reference to fix your code:
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
You can simply initialize and close connections by
using(SqlConnection con = new SqlConnection(connectionstring))
{
--write all your command n execution code here---;
}
Apart from this, one suggestion, you need to use parameterized query or Stored Proc with paramerts to avoid SQLInjection:
Reference to SQLInjection : https://www.veracode.com/security/sql-injection
I am trying to delete a selected row from a DataGridView which is linked to a Table in the database. Its stating the following error code.
Any ideas with where i am going wrong here?
Delete Button Code
private void DeleteExtraBtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
//Delete selected extra row
SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = #Extra_ID", con);
sda.Parameters.AddWithValue("#ExtraID", extraGridView.CurrentRow.Cells[0]);
sda.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
loadExtraTable();
}
I dont see you executing the command anywhere.
Add;
sda.ExecuteNonQuery();
Also you are referencing the cell object and not its value.
Also, you reference #ExtraID and #Extra_ID
private void DeleteExtraBtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
//Delete selected extra row
SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = #ExtraID", con);
sda.Parameters.AddWithValue("#ExtraID", extraGridView.CurrentRow.Cells[0].Value);
sda.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
loadExtraTable();
}
What is "ExtraId", a textbox, a string?
Depending on that, you have to use:
SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = #" + Extra_ID.Text, con);
I am trying to add data into table,but its not adding.I created conection, it should work.
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string insertQuery = "insert INTO Students(Firstname,Secondname,Telephone,IDCity,Dateofbirth,ID) values(#firstName,#secondName,#telephone,#idCity,#dateOfbirth ,#id)";
SqlCommand com = new SqlCommand(insertQuery, conn); //
com.Parameters.AddWithValue("#firstName", firstname.Text);//adding
com.Parameters.AddWithValue("#secondName", secondname.Text);//adding
com.Parameters.AddWithValue("#telephone", telephone.Text);//adding
com.Parameters.AddWithValue("#idCity", idcity.Text);//adding
com.Parameters.AddWithValue("#dateOfbirth", dateofbirth.Text);//adding
com.Parameters.AddWithValue("#id", id.Text);//
com.ExecuteNonQuery();
Response.Write("Registration is successful");
conn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True ");
con.Open();
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName'" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
where username **=**
forgot equality sign
Also, the conenction you open and the connection you use are different
The way I see it, you open a connection to the SQL server in Page_Load handler. But you don't close it.
If you try to open another one, or try to execute on a closed SqlConnection object, you might get an error.
A good way to do this is do something like this:
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
//do something here
}
catch (Exception)
{
/*Handle error*/
}
}
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source=MJ-PC;Initial Catalog=Test;Integrated Security=True");
con.Open();
}
catch
{
//Handles exceptions here
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
try
{
//SqlCommand cmd = con.CreateCommand();
SqlCommand cmd = new SqlCommand("select password from TestDemo where userName='" + txtusername .Text+ "'", con);
//cmd.Connection = con;
SqlDataReader da;
da = cmd.ExecuteReader();
if (!da.Read())
{
Response.Write("Wrong Details");
}
else
{
if(da[0].ToString()==txtusername.Text)
Response.Redirect("WebForm1.aspx");
else
Response.Write("Wrong Password");
}
}
finally
{
con.Close();
}
}
If you code for login, then here a neat version code, Depend on your flagset you can redirect or display wrong password msg
bool flagset=false;
SqlDataReader dr;
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select password from TestDemo where userName=#uName";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#uName", txtusername.Text);
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows){
while (dr.Read())
{
if(dr[0].ToString()==txtusername.Text)
{ flagset=true; }
}
}dr.Close();
con.Close();
}
}return flagset;