Update in ASP.NET - asp.net

I am using this code snippet to update values in my database :
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;Integrated Security=True");
string str = "sama#yahoo.com";
SqlCommand com2 = new SqlCommand("select [user_Account] from User in str where [user_Email]=sama#yahoo.com", con);
SqlCommand com = new SqlCommand("update User set [user_Account]=? WHERE [user_Email=#em]", con);
com.Parameters.AddWithValue("user_Account",str);
com.Parameters.AddWithValue("#em",str);
con.Open();
com.ExecuteNonQuery();
com2.ExecuteNonQuery();
con.Close();
but I get this error
Incorrect syntax near the keyword 'User'.
Line 40: com.ExecuteNonQuery();

"User" is a reserved word in SQL. Wrap the name of the table in square brackets to specify that it's the name of something:
[User]

Why are you using two separate SqlCommand objects?? Absolutely not needed..... I would try to either UPDATE or SELECT - don't mix two totally separate operations into a single call....
Also: you should use parametrized queries to avoid SQL injection attacks, and you should put your SqlConnection and SqlCommand objects into using blocks - try this:
string updateStmt =
"UPDATE dbo.[User] SET [user_Account] = #AccountValue WHERE [user_Email] = #UserEMail;";
using(SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;Integrated Security=True"))
using(SqlCommand _cmd = new SqlCommand(updateStmt, con))
{
_cmd.Parameters.Add("#AccountValue", SqlDbType.VarChar, 100).Value = str;
_cmd.Parameters.Add("#UserEMail", SqlDbType.VarChar, 100).Value = str;
con.Open();
_cmd.ExecuteNonQuery();
con.Close();
}

Related

I want my table to display all record if no searches were found for a movie but am unsure how to do that

This is my code, tell me where to change because When I do search for a movie that is in a record it displays the result, but when it isn't I only get "Movie Not Found" as in the response.write.
enter image description hereSLNkq.png
I would suggest to put question as text/code instead.
For your case, I suggest you to work with datatable instead of datareader.
== With Datatable approach ==
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=#MovieTitle) SELECT * FROM Content WHERE MovieTitle=#MovieTitle ELSE SELECT * FROM Content");
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Result");
da.Fill(dt);
con.Close();
MovieResults.DataSource = dt;
MovieResults.DataBind();
Based on #Shai Cohen's comment, it would be better approach by using ExecuteDataReader if transaction is forward-only. Thanks #ShaiCohen for your comment.
== Without Datatable approach ==
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("IF EXISTS(SELECT * FROM Content WHERE MovieTitle=#MovieTitle) SELECT * FROM Content WHERE MovieTitle=#MovieTitle ELSE SELECT * FROM Content");
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#MovieTitle", MovieTitle.Text);
cmd.Connection = con;
con.Open();
MovieResults.DataSource = cmd.ExecuteReader();
MovieResults.DataBind();
con.Close();
Enjoy Coding (;

Must declare the scalar variable "#Sid" in gridview while getting single record

while i'm trying to get single record from database table,based on login user details. i'm getting error,let me know where i'm doing wrong.
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
SqlConnection cn = new SqlConnection((cs));
cn.Open();
SqlCommand cmd = new SqlCommand("select * from Student_Details where Sid=#Sid", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.ExecuteNonQuery();
GridView1.DataBind();
Why you are executing query for select statement - cmd.ExecuteNonQuery(); not require..
You have to pass parameter value also
cmd.Parameters.AddWithValue("#sid", sid);
you missed this lines:
cmd.Parameters.AddWithValue("sid", User.Identity.Name)
and also cmd.ExecuteNonQuery(); is not necessary.

Data list results not disalying in my page

I tried the code below for displaying results in data list. When user logs in, I tried to pull the data according to their id, but the details do not display, here is my code:
string connn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(connn);
con.Open();
string str = "select details,address
from tb_userdata
inner join tb_userlogin
on tb_userdata.uidfromtb1=tb_userlogin.id";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Can any one tell me what is the problem with this code?
Your SQL query is missing WHERE statement. What you have in your query should show details for all users and not only for that specific user.
Try something like this and just update the part where parameter value is added
string connn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(connn);
con.Open();
string str = "select details,address from tb_userdata inner join tb_userlogin on tb_userdata.uid=tb_userlogin.id WHERE tb_userlogin.uid = #UID";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.Add(new SqlParameter("#UID", "retrieve UID somehow");
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
con.Dispose();

asp.net dropdownlist and gridview

I have created 2 DropdownList and 1 GridView
1st DropdownList Loads and Displays DataBase Names Dynamically
2nd DropdownList Loads and Displays Table Names, Based on Database name Which selected in 1st drop down list
Based on Table Name Data has to be displayed in GridView........
I have written code which displays Database Names and working fine
private void populateDatabasename() {
SqlConnection con = new SqlConnection(#"Data Source=SAI- PC\SQLEXPRESS;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name,collation_name from sys.databases order by name", con);
DataSet ds = new DataSet();
da.Fill(ds, "dbname");
DropDownList1.DataSource = ds.Tables["dbname"];
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();
}
Based on Database name tables have to be displayed..... how to pass Database name(Which is selected in 1st drop down list) in the following code.....
Is This a correct way to pass database name
private void populateTableName() {
SqlConnection con = new SqlConnection(#"Data Source=SAI-PC\SQLEXPRESS;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from "+"#Dbname"+".sys.tables", con);
da.SelectCommand.Parameters.Add("#dbname", SqlDbType.VarChar);
da.SelectCommand.Parameters["#dbname"].Value = DropDownList1.SelectedValue;
DataSet ds = new DataSet();
da.Fill(ds, "dbname1");
DropDownList2.DataSource = ds.Tables["dbname1"];
DropDownList2.DataTextField = "name";
DropDownList2.DataValueField = "name";
DropDownList2.DataBind();
}
I am not sure if it required or not but you should give the db name in connection string. Database=Northwind; in this case, using System.Data.SqlClient.SqlConnectionStringBuilder class even better. And then you can query the table names if the user have correct rights.
i think you should include DataBase name in connection string that you use to populate table
use something like this
SqlConnection con = new SqlConnection(#"Data Source=SAI-PC\SQLEXPRESS;Database=" + Dropdownlist1.selecteditem.text + ";Integrated Security=True");
then Read the tables and continue
Try this:
string dbName = ddlDbName.SelectedValue;
string strcon = "server=SAI-PC\\SQLEXPRESS;database= " + dbName + ";providerName=\"System.Data.SqlClient\"";
SqlConnection con = new SqlConnection(strcon);
con.Open();

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Resources