How to SETNOCOUNTOFF from the sql query - asp.net

i have a select staement which i use ExecuteNonQuery() property of SQL to return the number of affected rows. However this returns -1 all the times. I did research and realized its a result of SETNOCOUN ON property of SQL. Pls how do i off it from the query as i am not using stored procedure? Below is my code.
protected void txtName_Changed(object sender, EventArgs e)
{
string sql = "";
using (SqlCommand cmd = connection.CreateCommand())
{
sql = "SET NOCOUNT OFF;SELECT * FROM [CLIENT] WHERE cname = '" + txtName.Text + "'";
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
connection.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0 )
{
txtName.BackColor = System.Drawing.ColorTranslator.FromHtml("#FD5E53");
txtName.BorderColor = System.Drawing.ColorTranslator.FromHtml("#CD4A4A");
lblError.Text = "Client Exist.";
lblError.Visible = true;
lblError.Enabled = true;
btnInsertClient.Enabled = false;
pnlAddEdit_ModalPopupExtender.Show();
// return;
}
else
{
txtName.BackColor = System.Drawing.ColorTranslator.FromHtml("#F2F0E1");
txtName.BorderColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
lblError.Text = "";
lblError.Visible = false;
lblError.Enabled = false;
btnInsertClient.Enabled = true;
pnlAddEdit_ModalPopupExtender.Show();
}
connection.Close();
}
}

Don't use Execute**Non**Query():
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
Try ExecuteScalar() for example:
Executes the query, and returns the first column of the first row in the result set returned by the query.
Then make your query a COUNT().
Oh, and watch out for SQL injection and repetitive code.

Related

I see this error ORA-01722: invalid number when I want to insert data to oracle database table

I want to add answer table but I see error like 'Oracle.DataAccess.Client.OracleException (0x80004005): ORA-01722: invalid number '
DateTime localDate = DateTime.Now;
var culture = new CultureInfo("ru-RU");
var datenow = localDate.ToString(culture);
string[] splitdatenow = datenow.Split(' ');
cnn.Open();
OracleCommand cmdu = cnn.CreateCommand();
cmdu.CommandText = "INSERT INTO ANSWER (EXPLAIN,STATUS,USERID,QUESTIONID,CREATEDATE,MEDIA) VALUES (:comment_forms,'T',(SELECT ID FROM USERS WHERE MAIL=:mailSession) ,:send,:datef,:uploadf)";
cmdu.CommandType = CommandType.Text;
cmdu.Parameters.Add(new OracleParameter(":send",OracleDbType.Int32));
cmdu.Parameters.Add(new OracleParameter(":comment_forms", comment_form));
cmdu.Parameters.Add(new OracleParameter(":datef", splitdatenow[0]));
cmdu.Parameters.Add(new OracleParameter(":uploadf", upload_form));
cmdu.Parameters[":gelenid"].Value = gel;
cmdu.Parameters.Add(new OracleParameter(":mailSession",mailSession));
try
{
cmdu.ExecuteNonQuery();
}
catch(Exception ex)
{
Response.Write(ex);
}
cnn.Close();
Trigger for auto increment
create or replace
trigger ANSWERIDTRIGGER
BEFORE INSERT ON ANSWER
FOR EACH ROW
BEGIN
select ANSWERIDSEQ.nextval
into :new.ID
from dual;
END;

search data from database asp.net

protected void Button1_Click(object sender, EventArgs e)
{
string db = "Data Source=DESKTOP-R6H3RTP;Initial Catalog=AdmitDB; Integrated Security= true;";
SqlConnection mycon = new SqlConnection(db);
mycon.Open();
String query = "select * from tblPatient where PhoneNo like '"+TextBox1.Text+"%'";
SqlCommand cmd = new SqlCommand(query, mycon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (cmd.ExecuteNonQuery() > 0)
{
lblName.Visible = true;
lblId.Visible = true;
lblPNo.Visible = true;
lblDOB.Visible = true;
lblName.Text = "PName";
lblId.Text = "Pid";
lblPNo.Text = "PhoneNo";
lblDOB.Text = "PDOB";
}
else
{
lblNotFound.Visible = true;
}
}
i'm searching from database but just else statement executes don't know why it's not get data from database, if any kind of error then help me please
i think you don't need if (cmd.ExecuteNonQuery() > 0). the cmd executes automatically. you want to check the tables in the dataset.
// check the first table for rows.
if(ds.Tables[0].HasRows())
{
// success. now you can work with the table.
}
ExecuteNonQuery method returns the number of row that were modified by the query. Since SELECT query doesn't modify anything in the database - you get 0.
You should modify your query with a COUNT(*) function:
String query = "select COUNT(*) from tblPatient where PhoneNo like '"+TextBox1.Text+"%'";
Then you can get that value with ExecuteScalar():
if (cmd.ExecuteScalar() > 0)

How to get last incremented id in SQL with single query

My requirement I inserted successfully I want to bind last increment id to the root folder file name.id was automatic incremented in SQL. I want to bind last incremented id on that bold part place.
This is my code please help me to solve this problem:
string insert = "insert into Articles values('" + html+ "','" + text + "')";
try
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(#"~\Articles\**ID**.html"), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
}
finally
{
con.Close();
}
Please note that your code is a security risk as it's vulnerable to sql injection attacks as Sean Lange rightfully wrote in the comments.
Also, the empty catch is a problem as he pointed out. Do yourself a favor and never ever use empty catch blocks.
To get the last generated identity value in the current session you should use Sql Server's SCOPE_IDENTITY() function.
Note that if you have an instead of insert trigger on the table SCOPE_IDENTITY() will not give you the correct value.
Your code should look something like this:
string insert = "insert into Articles values(#html, #text); select scope_identity()";
using (var con = new SqlConnection("<YOUR CONNECTION STRING HERE>"))
{
using (var cmd = new SqlCommand(insert, con))
{
cmd.Parameters.Add("#html", SqlDbType.NVarChar).Value = html;
cmd.Parameters.Add("#text", SqlDbType.NVarChar).Value = text;
try
{
con.Open();
var databaseId = cmd.ExecuteScalar();
if (databaseId is int)
{
using (StreamWriter file = new StreamWriter(System.Web.Hosting.HostingEnvironment.MapPath(string.Format(#"~\Articles\{0}.html", databaseId)), true))
{
file.WriteLine(value.editor); // Write the file.
}
return msg;
}
else
{
return msg1;
}
}
catch (Exception ex)
{
// Write to log, show an error message to the user
}
}
}

Incorrect syntax near the keyword 'and'

I am trying to filter the gridview with the help of a few checkboxlists and it works absolutely fine.It is all real time since i am using a update panel.Now when i try to add one more filer i.e couple of datepickers to filter the gridview depending on the two dates,it gives me the error message " Incorrect syntax near the keyword 'and'.". The entire code is given below :
private void BindGrid()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
string query = "Select * from tblAllEvents";
string condition = string.Empty;
string conditionDisability = string.Empty;
string conditionDates = string.Empty;
foreach (ListItem item in cblGender.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" Where Gender IN ({0})", condition.Substring(0, condition.Length - 1));
}
else
{
condition = string.Format(" Where Gender IN ('Male','Female','Mixed')", condition.Substring(0,Math.Max(0,condition.Length - 1)));
}
foreach (ListItem item in cblDisability.Items)
{
conditionDisability += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(conditionDisability))
{
conditionDisability = string.Format(" and Disabled IN ({0})", conditionDisability.Substring(0, conditionDisability.Length - 1));
}
if(txtEventStart.Text == null)
{
txtEventStart.Text = "01/01/1900";
}
if(txtEventEnd.Text == null)
{
txtEventEnd.Text = "01/01/2050";
}
conditionDates = string.Format(" and EventStart between {0} and {1}",txtEventStart.Text,txtEventEnd.Text);
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(query + condition + conditionDisability + conditionDates))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Please note the problem arises on when i include 'conditionDates' in the query. What can be the other ways to make the query work.
Edit : As i said earlier, the problem lies in the below code
if(txtEventStart.Text == null)
{
txtEventStart.Text = "01/01/1900";
}
if(txtEventEnd.Text == null)
{
txtEventEnd.Text = "01/01/2050";
}
conditionDates = string.Format(" and EventStart between {0} and {1}",txtEventStart.Text,txtEventEnd.Text);
You are missing apostrophes around the values:
conditionDates = string.Format(" and EventStart between '{0}' and '{1}'", txtEventStart.Text, txtEventEnd.Text);
Note however that code like this is wide open for SQL injection attacks. You should use parameters in the query instead:
conditionDates = " and EventStart between #EventStart and #EventEnd";
Then you add parameters to the command object parameter collection to supply the values to the query:
cmd.Parameters.Add("#EventStart", SqlDbType.DateTime).Value = txtEventStart.Text;
cmd.Parameters.Add("#EventEnd", SqlDbType.DateTime).Value = txtEventEnd.Text;
You clearly have a SQL syntax error. First debug your code and get the resulting query and run it separately in SQL Server. You will inspect it better in that way.
It's about how you are concatenating the SQL query when you add that part.

Update in GridView "No value given for one or more parameters"

I have this code (below) and I am getting the following error:
No value given for one or more parameters
But when it is run again, values are shown updated for 'RateCenterName', 'QuantityThreshold', 'RateCenterID' but not for 'Province'
The code:
string updateSql = "UPDATE RateCenters SET RateCenterName = ?, Province=?, QuantityThreshold = ?" + " WHERE RateCenterID= ?";
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ddl = (DropDownList)row.FindControl("DropDownList2"); // assigning the dropdownlist item to 'ddl'
TextBox rateCenterName = (TextBox)row.FindControl("txtRateCenterName"); // assigning textbox input item
TextBox quantityThreshold = (TextBox)row.FindControl("txtQuantityThreshold"); // assigning textbox input item
Label ratecenterid = (Label)row.FindControl("Label1"); // assigning the label value
//OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\arjun.giridhar\My Documents\Visual Studio 2010\Projects\BillingApplicationNew\BillingApplicationNew\App_Data\db1.mdb;Persist Security Info=False");
OleDbCommand cmd = null;
try
{
cmd = new OleDbCommand(updateSql, conn);
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = rateCenterName.Text;
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = ddl.SelectedItem.Text;
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = Convert.ToUInt32(quantityThreshold.Text);
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = Convert.ToInt32(ratecenterid.Text);
conn.Open();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
//GridView1.EditIndex = -1; //refreshing
//GridView1.DataBind();
}
catch (OleDbException ex)
{
throw (ex);
}
finally
{
conn.Close();
conn.Dispose();
}
}
Can anyone see what's wrong?
Moderator edit:
He solved the problem, but his solution is deep inside one of the comment threads:
I got it, i removed the Row updating event and just tried it once
again without adding that event.
I think he means: he took this code out of the RowUpdating event handler and put it elsewhere.
there might be Problem in your code because you are trying to edit access database and you are writing code of sqldatabase....
You Update Statement code
string updateSql = "UPDATE RateCenters SET RateCenterName =?, Province=? ,
QuantityThreshold = ? WHERE RateCenterID= ?";
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("RateCenterName", str2);
cmd.Parameters.AddWithValue("Province", str3);
cmd.Parameters.AddWithValue("QuantityThreshold ", str4);
cmd.Parameters.AddWithValue("RateCenterID", str5);
con.Open();
cmd.ExecuteNonQuery();
}
}
You have a missing space before WHERE when you are building your SQL.
Line 2 in your sample code.
"WHERE RateCenterID= #RateCenterID"; // this the error. you need to provide space before where
you need to add space before Where .
this you should try
string updateSql = "UPDATE RateCenters SET RateCenterName = #RateCenterName, Province=
#Province, QuantityThreshold = #QuantityThreshold" + " WHERE RateCenterID= #RateCenterID";
The most likely problem is passing a null value to either RateCenterName or Province.
What happens when you try this:
cmd.Parameters.Add("#RateCenterName", OleDbType.VarChar).Value = "rateCenter";
cmd.Parameters.Add("#Province", OleDbType.VarChar).Value = "ddl";
cmd.Parameters.Add("#QuantityThreshold", OleDbType.Integer).Value = 0;
cmd.Parameters.Add("#RateCenterID", OleDbType.Integer).Value = 1;

Resources