Use a variable in update statement ASP.NET in SQL - asp.net

I want to use variable name as column name in ASP.NET column name.
I'm getting the following error:
Incorrect syntax near 'February'.
The code is
SqlConnection MyConn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\apptitude\projects\database\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
MyConn.Open();
int i,n=5;
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;
Label1.Text = day.ToString();
if (day==1)
{
//for(i=1;i<=n;i++)
//{
//Label1.Text = "hi";
int j = 1;
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set **'"+month[mon]+"'=20";**
i = cmd.ExecuteNonQuery();
Label1.Text = i.ToString();
}

You don't need to enclose column names in single quotes ('); hence this:
update Yearly_data set 'February'=20
Should be written as
update Yearly_data set February=20
If you change your code to the below, it will work:
cmd.CommandText = "update Yearly_data set "+month[mon]+"=20";
However, note that building Dynamic SQL statements is something that should be carefully done as not to risk your app on a SQL Injection attack.

If every month of the year is a ColumnName in Yearly_data then change your line of code to:
cmd.CommandText = "update Yearly_data set ["+month[mon]+"]=20";

In addition to the answers already given, the framework provides a way to get the name of the month using the DateTimeFormatInfo.GetMonthName function.
static string GetMonthName(DateTime sourceDate)
{
var dateFormatInfo = new DateTimeFormatInfo();
return dateFormatInfo.GetMonthName(sourceDate.Month);
}
cmd.CommandText = String.Format("update Yearly_data set {0} = 20", GetMonthName(DateTime.Now));

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

My SqlDatareader was not working

I have a code for fetching customer_id and I use a SqlDataReader for reading customer_id from SQL Server. I test witch using breakpoint and step by step debugging and I understand the SqlDataReader condition was not compile and compiler jump straight in to the connection.close line:
string strQuery = "select customer_id from Registration where username=#username and password=#password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
string customer_id = cmd.ExecuteScalar() as string;
connection1.Close();
if (customer_id == null)
{
Messages myMsg = new Messages();
myMsg.CreateMessageAlert("The User does not Registered or your using incorect username or password");
}
else {
Session["customer_id"] = customer_id;
}
Although the issue is not very clear, you can try to revise the code taking following into account:
There is no need to open/close db connection for every sql query in a method. Open it once, execute all queries, close. That will make code clear and faster.
As you take connection from somewhere else, make sure it is closed before you open it (Example: Check if SQL Connection is Open or Closed)
You run 2 queries and in both cases you get only 1 result (select count(*), select customer_id). Why then in first case you do ExecuteScalar() and ExecuteReader() in the other?
The other thought is there is no need to have 2 SqlCommand(), etc if you need to return results of 2 queries. Read about Retrieving Multiple Result Sets using NextResult
And last but not least - it seems you need to check if user is already registered and if true, get his id. Why not do it in one shot? The second query is good for both cases - if user does not exist, query will not return any result, if he does - his id will be returned. Doing this way, you would need only one query and less coding.
UPDATE:
The updated code looks more clear and straightforward, but you didn't get the point of my last comment. If you select count(customer_id) you get a count that you don't need. Why not simply select customer_id and check if it was returned or not?
Example:
//string strQuery = "select count(customer_id) from Registration where username=#username and password=#password";
string strQuery = "select customer_id from Registration where username=#username and password=#password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
//int intRowCount = (int)cmd.ExecuteScalar();
string customer_id = cmd.ExecuteScalar() as string;
//txt1_username.Text = intRowCount.ToString(); <-- What's this?
connection1.Close();
//if (intRowCount == 1)
if (customer_id == null)
{
// user does not exist, because sql returned no rows
... <-- do something here
} else {
Session["customer_id"] = customer_id;
}
UPDATE #2:
To troubleshoot
Make sure txt1_username.Text and txt2_password.Text have expected values. It could be that you reset the Text somewhere and that could be the reason why the query returned no result. Try to hardcode the value in the code, for example,
cmd2.Parameters.AddWithValue("username", "admin");
cmd2.Parameters.AddWithValue("password", "123");
Copy-paste entire sql in Sql Server Management Studio (or other tool) and run it from here to ensure what result it returned.
Make sure you execute it against correct database (maybe you have different databases with same tables where data is different).
This is because your username is no longer the username. It is actually 1 because of the line
int intRowCount = (int) cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString(); <-- RED FLAG
So in the inside the If, you are actually running
SELECT customer_id FROM registration WHERE username=1 and password=my_password
Comment line 15 and you should do fine.
updated
string strQuery = "select count(*) from Employee where FullName=#username";
SqlConnection connection = DBConnection.getConnection();
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);
int intRowCount = (int)cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString();
if (intRowCount == 1)
{
string strquery = "select customer_id from Registration where username=#username and password=#password";
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = connection;
cmd2.CommandText = strquery;
cmd2.Parameters.AddWithValue("username", txt1_username.Text);
cmd2.Parameters.AddWithValue("password", txt2_password.Text);
SqlDataReader reader = cmd2.ExecuteReader();
if (reader.Read())
{
string customerID = reader[0].ToString();
}
}
connection.Close();`
This is complete solution for your issue.
Do not need to open connection everytime. just make sure, connection is being closed once it's used.

Error converting nvarchar to int in ExecuteNonQuery

I am getting an error for the following program in asp.net.
I have checked sql and name is in nvarchar.
{
con.Open();
SqlCommand cmd = new SqlCommand("bookinsertion2", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#idnumber",txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#year", txtyear.Text);
cmd.Parameters.AddWithValue("#department", txtdepart.Text);
cmd.Parameters.AddWithValue("#bookname", ddlbookavail.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/LendingForm2.aspx");
}
This is the code of the stored procedure
create Procedure [dbo].[bookinsertion2]
#idnumber int,
#name nvarchar(20),
#year int,
#department nvarchar(30),
#bookname nvarchar(25)
as
Begin
insert into tbllendinginfo values(#idnumber,#name,#year,#department,#bookname)
insert into tbllendinginfo(Dateofbooktaken) values(GETDATE())
update tblbookinfo set BooksAvailable=BooksAvailable-(select COUNT(Id) from tbllendinginfo where BookName=#bookname) where Name=#bookname
end
The error is " Conversion failed when converting the nvarchar value 'Mike' to data type int. "
The error message is clear, one or more of the parameters expected by the stored procedure are not of type nvarchar. Probably the #year and #idnumber parameters are an integers. If that's true then you need to call
cmd.Parameters.AddWithValue("#idnumber",Convert.ToInt32(txtid.Text));
cmd.Parameters.AddWithValue("#year", Convert.ToInt32(txtyear.Text));
Said that, please try, if possible to avoid the call to AddWithValue, in particular in case where strings or date are involved. AddWithValue determines the type of the parameter from the input value and most of the time is correct, but there are situations where it decides for a wrong datatype and the errors are difficult to find. Moreover AddWithValue with strings is a performance hurdle.
A better explanation could be found in these two articles.
Can we stop using AddWithValue() already?
How Data Access Code Affects Database Performance
You could rewrite the code above using the Object Initializer Syntax
{
con.Open();
SqlCommand cmd = new SqlCommand("bookinsertion2", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#idnumber",
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(txtid.Text)
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#name",
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = txtname.Text
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#year",
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(txtyear.Text)
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#department",
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = txtdepart.Text
});
cmd.Parameters.Add(
new SqlParameter
{
ParameterName = "#bookname",
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = ddlbookavail.SelectedItem.ToString()
});
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/LendingForm2.aspx");
}
EDIT
After your edit I think the problem is in this line of the stored procedure:
insert into tbllendinginfo values(#idnumber,#name,#year,#department,#bookname)
You haven't specified the columns' names but just the parameters. So the server inserts the parameter following the order of definition of the columns in the datatable.
Of course, if the second column in the table is not the column that should receive the #name parameter you could have serious problems.
You could fix the problem listing the name of the columns in the same order iun which you put the parameter inside the VALUES clause or changing the order of the parameters to follow the order of the column names.
For example (I don't know the column names so you should fix them)
insert into tbllendinginfo (idnumber, name, bookyear, department, bookname)
values(#idnumber,#name,#year,#department,#bookname)

using the querystring parameter in my where clause to generate insert operation

here,using request.Querystring i find the companyname and job title of particular Job.when user logsin using username in texbix.i want the Companyname,jobtitle and username in the same row of a table.But when i generate my query it inserts the (companyName & jobtitle) in the first row and username in second row.How can i fulfill my task.Some people said,i have to keep the companyname and jobtitle in a variable...then execute.
is it a parfect solution?
if it is,how can i do that?
code:
protected void ButtonApply_Click(object sender, EventArgs e) {
String str = Request.QueryString.Get("JobNo");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CompanyName,JobTitle) select CompanyName,JobTitle from Jobs where JobNo='"+str+"'" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
try {
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("ApplyJob.aspx?JobNo="+str);
}
in the apply.aspx i have following code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CandidateInformation) Values (#CandidateInformation)" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation", TextBoxaun.Text);
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
Inserting two times will always result in two new rows.
You can do it all in the first insert statement:
string apply = "INSERT INTO Company (CompanyName,JobTitle, CandidateInformation) select
CompanyName,JobTitle, #CandidateInformation from Jobs where JobNo=#JobNo ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation",
TextBoxaun.Text);
insertApply.Parameters.AddWithValue("#JobNo", str);
try
{
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
}
Then you won't need the second page.
Use
Update Company Set CandidateInformation = #CandidateInformation where JobNo='"+str+"'" ;
instead of
string apply = "INSERTINTO Company (CandidateInformation) Values
(#CandidateInformation)" ;
If you will use Insert statement again, then it will always create new record in the table.
Update is used to update an already existing record of the table.

invalid column value in where clause in sql server

I have a function which would populate a datatable with the contents of a table. But its showing an annoying invalid column name error with the value I give in the WHERE clause.
public static DataTable GetRequests(string empid)
{
DataTable dt = new DataTable();
string strConnection = ConfigurationManager.AppSettings["connStr"];
using (SqlConnection connection = new SqlConnection(strConnection))
{
connection.Open();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sAdap = new SqlDataAdapter();
sqlcmd.Connection = connection;
sqlcmd.CommandType = System.Data.CommandType.Text;
sqlcmd.CommandText = "Select * from requests Where emp_id=P001";
sAdap.SelectCommand = sqlcmd;
sAdap.Fill(dt);
}
return dt;
}
Now with this i am getting the error at
sAdap.fill
and the error is
invalid column name P001
I'm stumped at this. Any ideas why I'm facing this issue?
If it's a string constant, surround it with single quotes. 'P001' or better still, paramaratise it.
You need string delimiters around the value. Change the line to:
sqlcmd.CommandText = "Select * from requests Where emp_id='P001'";
with the single quotes around P001 and you should be fine.
You need to use single quote.
where emp_id='P001'
It looks like your P001 data is a string type. Try quoting it with single quotes before feeding it in as an sql string.
sqlcmd.CommandText = "Select * from requests Where emp_id='P001'";
If that doesn't work (though it should) you can try the like statement as in:
sqlcmd.CommandText = "Select * from requests Where emp_id like 'P001'";
You need to surround your (apparrently) text criteria with single quotes:
sqlcmd.CommandText = "Select * from requests Where emp_id = 'P001'";

Resources