update query is not working in ASP.NET web application - asp.net

using System.Data.SqlClient;
using System.Data.Sql;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=GAGAN-PC\SQLEXPRESS;Initial Catalog=update_test;Integrated Security=True");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void delete_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("delete from update_delete where id like'"+TextBox1.Text+"'",con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully deleted.");
}
protected void update_button_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("update update_delete set password ='"+TextBox3.Text+"' where id like'"+TextBox2+"'", con);
cmd.ExecuteNonQuery();
Response.Write("Control reached.");
con.Close();
Response.Write("Data successfully Updated.");
}
}
I am trying to implement update query but there is a little problem in it. I have used SQL Server as database and update_delete is a table in which there are 3 columns id,sname,password and I am trying to update password with respect to id.
Problem is when I click on update button control reaches cmd.ExecuteNonQuery(); no error is displayed. but updating is not taking place. what should I do. Please Please Please help me. Thanks in advance. :) :)

I'm just guessing here - if Id is a numeric datatype, then you cannot use LIKE with it.
Also: please use using()... blocks to ensure proper disposal and use parametrized queries to avoid SQL Injection attacks.
Write your UPDATE command like this:
protected void update_button_Click(object sender, EventArgs e)
{
// get the values to use
string idValue = Convert.ToInt32(TextBox3.Text.Trim());
string password = TextBox2.Text.Trim();
// define the query text with *parameters* !
string updateQuery = "update update_delete set password = #password where id = #ID";
// put things like SqlConnection and SqlCommand into "using()...." blocks
using (SqlCommand updCmd = new SqlCommand(updateQuery, con))
{
// define parameters and their values
updCmd.Parameters.Add("#password", SqlDbType.VarChar, 50).Value = password;
updCmd.Parameters.Add("#ID", SqlDbType.Int).Value = idValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Data successfully Updated.");
}
}

I suppose you get an Exception. I would kindly suggest to catch your exception and tell us the message... You can catch the exception using the debugger or a try-catch clause.
If you don't get an exception and "Control reached" message is displayed, you would have to use the formed SQL string to use it directly in SQL Server and see if there is a mistake in the SQL statement. I suppose that you somehow form an invalid SQL statement (eg using a non-existing ID).
Hope I helped!

Related

Asp .net dropdownlist data keep load

After I get the value show in GridView the DropDownList will contain duplicate items when I click again.
public void Page_Load(object sender, EventArgs e)
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
public void button_click(object sender, EventArgs e)
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
You should write it as:
public void Page_Load
{
if (!IsPostBack){
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
}
public void button_click
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
The Page_Load method is called each time a postback occurs (such as when you click on an ASP.NET button control). The data was already added on the first load and stored in ViewState. On the second request, it adds it again. You can detect whether you're in a postback by using the Page.IsPostBack property.
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// add items to drop down list
}
}
Side note, make sure that any objects that implement the IDisposable interface are handled properly. You need to make sure they're disposed when you're done with them to avoid hard to diagnose errors. You can either call .Dispose() on them in a finally block or you can wrap them in a using statement. Your SqlCommand, SqlConnection (this should not be a property/field)andSqlDataReaderall implementIDisposable`.
I just found the solution. Put the if(!Ispostback) in the page load statement there.
At best-guess, without compile-able code, it looks like your Dropdown List is persisted between page loads, meaning it's never going out of context (the object remains in memory). So, it is just getting appended over and over each time there is a page load. You probably want to do a check for existing values:
public void Page_Load()
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con)) {
using(SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
//Have not tested the if statement... may need to correct it.
if(!DropDownList1.Items.Contains(dr[0].ToString())) {
DropDownList1.Items.Add(dr[0].ToString());
}
}
}
}
con.Close();
}

Using many sql connection in one code?

I have an ASP.NET web application which is connected to SQL Server.
I have used three connections for each SQL operation. It works very well, however I think this is not an efficient way to do things - can this be written better than it is?
public partial class Home : System.Web.UI.Page
{
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
co.Close();
using (con)
{
con.Open();
SqlCommand cmv = con.CreateCommand();
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
con.Close();
using (con2)
{
con2.Open();
SqlCommand cmf = con2.CreateCommand();
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
con2.Close();
}
}
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = "select...";
cm.CommandText += " insert...";
cm.CommandText += " delete from...";
cm.ExecuteNonQuery();
}
co.Close();
}
you can use like this.
You're using the same connection string for each connection? Why do you need three connections? Why not just open and close the same one?
As long as the connection string is the same, you only need one connection.
In general you should prefer to create and open a connection object as close to where you make use of it as possible, and dispose of it as soon as possible afterwards (preferably by making use of a using statement). Connection pooling will take care of ensuring you only actually create a limited number of real connections to the server, despite the large number of SqlConnection objects your code may seem to create.
Within a single method, however, it is reasonable to use a single connection object:
public partial class Home : System.Web.UI.Page
{
string connString = ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString;
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection co = new SqlConnection(connString))
{
co.Open();
using(SqlCommand cm = co.CreateCommand())
{
cm.CommandText = "select...";
cm.ExecuteNonQuery();
}
using(SqlCommand cmv = co.CreateCommand())
{
cmv.CommandText = "insert...";
cmv.ExecuteNonQuery();
}
using(SqlCommand cmf = co.CreateCommand())
{
cmf.CommandText = "delete from...";
cmf.ExecuteNonQuery();
}
}
}
}
(You don't need to explicitly close the connection object, the Dispose (within the using is equivalent)
No use declaring/creating multiple connections when you would be using only one at a time. You can do with just one.
Declare variable as close as possible to its first use, and with minimum scope manageable.
Make things modular and reusable as far as possible.
No need to explicitly close the connection, since the IDisposable interface implementation (and using block) does it anyways. But there is no harm in explicitly closing it.
protected void Button1_Click(object sender, EventArgs e)
{
ExecuteNonQuery("select...", null); // why??
ExecuteNonQuery("insert...", null);
ExecuteNonQuery("delete from...", null);
}
protected void ExecuteNonQuery(string query, SqlParameter[] parameters)
{
using (SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString))
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = query;
if (parameters != null) cm.Parameters.AddRange(parameters);
cm.ExecuteNonQuery();
}
}
You can also try this.
SqlConnection co = new SqlConnection(ConfigurationManager.ConnectionStrings["TextConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(" Select statement.. ");
sb.AppendLine(" Insert statement ");
sb.AppendLine(" delete statement ");
using (co)
{
co.Open();
SqlCommand cm = co.CreateCommand();
cm.CommandText = sb.Tostring();
cm.ExecuteNonQuery();
}
co.Close();
}

How to save Video file in DB?

I have a task to insert Video in DB and display it by Html5 video control. I did my code well and the video saved well in DB but when I tried to play the video it doesn't and when I checked my code I found that the video saved in DB with this path ~/res/Files/. When I
removed the ~/ as the path will be res/Files/ it worked well. How can I solve this issue?
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
btier.AddObject("~/res/Files/" + FUFile.FileName);
FUFile.SaveAs(Server.MapPath("~/res/Files/" + FUFile.FileName));
}
The reason being, you are passing the path as a string parameter to your method AddObject and to MapPath. Hence the path will remain "~/res/..." instead of resolving to the application root.
You have to first resolve the root and then save that path. One safe option is to use VirtualPathUtility. Something like this:
tempVar = VirtualPathUtility.ToAbsolute("~/res/Files/" + FUFile.FileName);
btier.AddObject(tempVar);
FUFile.SaveAs(Server.MapPath(tempVar));
Where tempVar is a string variable.
protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
cmd.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
cmd.Parameters.AddWithValue("#ContentType", "video/mp4");
cmd.Parameters.AddWithValue("#Data", bytes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
Complete step by step tutorial:
http://www.aspsnippets.com/Articles/Upload-Save-Retrieve-and-Play-MP4-Video-files-with-live-streaming-from-Database-in-ASPNet-using-C-and-VBNet.aspx

Database does not exist

Here is my code to back up a database.
These are my databases:
I got this as Error:
Database 'BakupDB' does not exist. Make sure that the name is entered
correctly. BACKUP DATABASE is terminating abnormally.
And the code for my web page:
public partial class Default2 : System.Web.UI.Page
{
string dbname = "BakupDB";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
//Mentioned Connection string make sure that user id and password sufficient previlages
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
//Enter destination directory where backup file stored
string destdir = "D:\\backupdb";
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database "+dbname+" to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
Response.Write("Backup database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}
}
}
What do I wrong?
It looks like you're trying to use a User Instance. As an aside (not 100% related to your question) I believe that this feature is deprecated in SQL Server Express 2012 (and have been on a deprecation path since SQL Server 2008).
Sorry for the aside. With regards to your question perhaps the following will help you:
Stack Overflow question
Accomplishing the task using SMO
I would say the Stack Overflow question is closer to the use case you're trying to achieve with executing the SQL command, but have referenced the SMO way in case you were interested or wanted to try a different approach. Based on the SO question it appears that your connection string:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True";
Is missing a Database= section so perhaps it should read like:
sqlcon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BakupDB.mdf;Integrated Security=True;User Instance=True;Database=BakupDB";
This code worked for me:
private void button5_Click(object sender, EventArgs e)
{
try
{
string dlink= #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\jsdb.mdf; Database=jsdb; User Instance=True; Integrated Security=True;Asynchronous Processing= True";
SqlConnection dcc = new SqlConnection(dlink);
dcc.Open();
string database = "jsdb";
string blc = textBox1.Text; //(Its the location to save the file)
string nm = "dbBackup";
string dt =DateTime.Today.ToShortDateString();
string sl = "BACKUP DATABASE "+database+" TO DISK = '"+blc+"\\"+nm+"-"+dt+".bak'" ;
SqlCommand cql = new SqlCommand(sl,dcc);
cql.ExecuteNonQuery();
MessageBox.Show("Database backup completed successfully..");
dcc.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}

Execute Query from another function

I want to execute a query on a button click event.
But that query is written in another function.
Here is my code, and it's not working. What is my problem?
namespace MCE_Member_Registration
{
public partial class registration_form_view : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
createform();
}
protected void createform() {
NameValueCollection nvc = Request.Form;
surname.Text = nvc["txt_surname"];
cmd.CommandText = "Insert into mce_applicants_information values(N'" + nvc["txt_surname"] + "')";
}
protected void confirm_Click(object sender, EventArgs e)
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
I'm not sure if this solves your problem. But if you really need another method to create your command, let it return it.
protected SqlCommand GetCommand()
{
SqlCommand cmd = new SqlCommand("Insert into blahblah values(blahblah)", connection);
return cmd;
}
protected void Button1_Click() {
connection.Open();
GetCommand().ExecuteNonQuery();
connection.Close();
}
Note that this is not best-practise due to several reasons. The connection should be closed even if an exception occured so use using statement instead. But that would be a problem in this approach since the connection is a field.
So i would prefer the all-in-one method approach which also uses parameters tro prevent sql-injection attacks:
protected void Button1_Click()
{
ExecuteBlahBlahCommand("blahblah");
}
private void ExecuteBlahBlahCommand(string blaColumnVal)
{
const string sql = "Insert into blahblah values(#blaColumn)";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#blaColumn", blaColumnVal);
con.Open();
cmd.ExecuteNonQuery();
}
}
I suggest you to use CommandText property and not contructor, because instance of cmd is created before this code, so you adjust your property
protected void CreateQuery() {
cmd.CommandText = "Insert into blahblah values(blahblah)";
}
protected void Button1_Click() {
connection.Open();
CreateQuery();
cmd.ExecuteNonQuery();
connection.Close();
}
Answering the question itself - Any variable you declare inside a function cannot be seen outside that function. You need to declare the SqlCommand in the correct scope...
For instance:
SqlCommand cmd;
protected void CreateQuery()
{
cmd = new SqlCommand("Insert into blahblah values(blahblah),connection)";
}
protected void Button1_Click()
{
CreateQuery();
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
This will declare the variable in the class level, and be accessible to all other methods in that class.
I'll just mention that #Tim Schmelter's answer is a good solution that might better suit your needs.

Resources