This is my cs code
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString());
con.Open();
SqlCommand com = new SqlCommand("update slab set salbn = #salbn,basic = #basic,hra = #hra,trvl = #trvl,mdeca = #mdeca,atnd = #atnd,tote = #tote where salbn = #salbn", con);
com.Parameters.Add("#salbn", DropDownList1.SelectedItem.Text);
com.Parameters.AddWithValue("#salbn", TextBox21.Text);
com.Parameters.AddWithValue("#basic", TextBox12.Text);
com.Parameters.AddWithValue("#hra", TextBox13.Text);
com.Parameters.AddWithValue("#trvl", TextBox15.Text);
com.Parameters.AddWithValue("#mdeca", TextBox16.Text);
com.Parameters.AddWithValue("#atnd", TextBox18.Text);
com.Parameters.AddWithValue("#tote", TextBox20.Text);
com.ExecuteNonQuery();
con.Close();
MsgBox("Updated Successfully");
}
I got error
The variable name '#salbn' has already been declared. Variable names must be unique within a query batch or stored procedure. Must declare the scalar variable "#basic"
I am using C# and SQL Server
Well, just as it says: you are adding a parameter named salbn twice. Once just below SqlCommand com = ... and the second time on the next line.
In your query you have two parameters with the same name #salbn. No problem, but you cannot add two times in the Parameters collection. I've seen your code have two controls for the same parameters, for change the name of one of them, for sample:
SqlCommand com = new SqlCommand("update slab set salbn = #salbnValue, basic = #basic, hra = #hra, trvl = #trvl, mdeca = #mdeca, atnd = #atnd, tote = #tote where salbn = #salbn", con);
com.Parameters.Add("#salbnValue", DropDownList1.SelectedItem.Text);
com.Parameters.AddWithValue("#salbn", TextBox21.Text);
Related
I have the code below (I've included what I believe are all relevant sections):
private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_# = ?;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.Add(new MySqlParameter("", val1));
m.Parameters.Add(new MySqlParameter("", val2));
MySqlDataReader r = m.ExecuteReader();
if (r.HasRows)
level = Convert.ToInt32(r.GetValue(0).ToString());
r.Close();
return true;
}
When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
Try this instead:
private String readCommand =
"SELECT LEVEL FROM USERS WHERE VAL_1 = #param_val_1 AND VAL_2 = #param_val_2;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.AddWithValue("#param_val_1", val1);
m.Parameters.AddWithValue("#param_val_2", val2);
level = Convert.ToInt32(m.ExecuteScalar());
return true;
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
MySqlConnection con = new MySqlConnection("server=localhost;User Id=root;database=result;password=1234");
con.Open();
MySqlCommand cmd = new MySqlCommand("Select * from users where username=?username and password=?password", con);
cmd.Parameters.Add(new MySqlParameter("username", this.Login1.UserName));
cmd.Parameters.Add(new MySqlParameter("password", this.Login1.Password));
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows ==true)
{
e.Authenticated = true;
}
}
You need to use named parameters in your query. E.g.:
String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ?param1 AND VAL_2 = ?param2";
Then, pass the parameter names when you instantiate your MySqlParameter objects like so:
m.Parameters.Add(new MySqlParameter("param1", val1));
m.Parameters.AddWithValue("parameter",value)
will be better option for parametrized query.
I don't think the MySql.Data classes support unnamed parameters. If you're keen to use them, you could access your MySql db via the Odbc drivers, they support this.
You'll need to name the parameters in your query:
"SELECT LEVEL FROM USERS WHERE VAL_1 = #val1 AND VAL_2 = #val2;"
I've chosen the param indicator "#", but recent versions of MySql.Data support both "#" and "?".
Then update your param constructor to pass in the correct param name (you don't need to include the param indicator here, although it doesn't make any difference if you do).
m.Parameters.Add(new MySqlParameter("val1", val1));
PS. You prob know this already, or it was just omitted in the snippet, but I think you forgot to call Read on your instance of ExecuteReader.
If you want to execute the sql many times, then you should use this way:
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
cmd.ExecuteNonQuery();
}
First time is without "ExecuteNonQuery" just adding the parameters with faked values, then inside the loop you add the real values.
See this link:
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html
I am developing a system that is to have GridView with a select option to select the data stored in a particular row by its primary key ID.
This code works just fine on another page to perform the exact same functionality
protected void lnk_OnClick(object sender, EventArgs e)
{
int objectiveID = Convert.ToInt32((sender as LinkButton).CommandArgument);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("objectiveViewByID", con);
sqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlDa.SelectCommand.Parameters.AddWithValue("#objectiveID", objectiveID);
DataTable dtbl = new DataTable();
sqlDa.Fill(dtbl);
con.Close();
hfobjectiveID.Value = objectiveID.ToString();
txtAudience.Text = dtbl.Rows[0]["audience"].ToString();
txtCondition.Text = dtbl.Rows[0]["condition"].ToString();
txtBloom.Text = dtbl.Rows[0]["bloom_level"].ToString();
txtVerb.Text = dtbl.Rows[0]["verb"].ToString();
txtProduct.Text = dtbl.Rows[0]["product"].ToString();
btnSave.Text = "Update";
btnDelete.Enabled = true;
}
I expect the code to repopulate the input fields that were used to populate the database.
In theory, a format exception, it could give an error here if the ToInt32 method input is some non number value.
int objectiveID = Convert.ToInt32((sender as LinkButton).CommandArgument);
Other potential areas are the following code, if the value, for instance, dtbl.Rows[0]["audience"] is null.
But that would be a different exception though. You could put a break point at the top and see which line crashing.
hfobjectiveID.Value = objectiveID.ToString();
txtAudience.Text = dtbl.Rows[0]["audience"].ToString();
txtCondition.Text = dtbl.Rows[0]["condition"].ToString();
txtBloom.Text = dtbl.Rows[0]["bloom_level"].ToString();
txtVerb.Text = dtbl.Rows[0]["verb"].ToString();
txtProduct.Text = dtbl.Rows[0]["product"].ToString();
I declared already so why do I get an error?
conn.Open();
String strCount = "Select SUM(freight) AS TOTAL from Orders where EmployeeID = #employee AND Year(OrderDate)= #Oyear";
SqlCommand cmdCount = new SqlCommand(strCount, conn);
cmdSelect.Parameters.AddWithValue("#employee", DropDownList1.SelectedValue.ToString());
cmdSelect.Parameters.AddWithValue("#Oyear", RadioButtonList1.SelectedValue.ToString());
double intCount = (double)cmdCount.ExecuteScalar();
Label1.Text = intCount.ToString();
conn.Close();
You are adding the parameters to the wrong command.
Change the command name you add the parameters to, and it will work:
cmdCount.Parameters.AddWithValue("#employee", DropDownList1.SelectedValue.ToString());
cmdCount.Parameters.AddWithValue("#Oyear", RadioButtonList1.SelectedValue.ToString());
I have a webservice that searches the database for the stored templates. However, I get the error when running my application
Must declare the scalar variable "#Template".
[WebMethod]
public Verification StuVerification (byte[] Template)
{
cn.Open();
SqlCommand com = new SqlCommand("SELECT * FROM tblFingerprint WHERE Template = #Template)", cn);
SqlDataReader sr = com.ExecuteReader();
while (sr.Read())
{
Verification verification = new Verification()
{
StudentID = sr.GetInt32(0),
StudentNumber = sr.GetString(1),
Name = sr.GetString(2),
Surname = sr.GetString(3),
};
cn.Close();
return verification;
}
cn.Close();
return new Verification();
}
Verification ver = verification.StuVerification(m_VrfMin);
Verification v = new Verification();
if (ver.StudentID > 0)
{
// Verification v = new Verification();
richTextBox1.Text = v.StudentNumber;
}
else
{
richTextBox1.Text = "Verification Failed" + error;
}
You haven't added the SQL parameter to the SQLCommand:
com.Parameters.AddWithValue("#Template", TemplateObject);
The #Template string in your command text is a placeholder for a parameter that you should define in your command parameters collection together with a value to pass to the database code.
cn.Open();
SqlCommand com = new SqlCommand(#"SELECT * FROM tblFingerprint
WHERE Template = #Template", cn);
com.Parameters.AddWithValue("#Template", Template);
SqlDataReader sr = com.ExecuteReader();
Its value is used in the execution of your query to select the rows that will be returned by the query. However, it is not clear, from your code above what is the datatype of the field Template in your database table. As is, this code passes a byte array in the form of a binary datatype and this could not be the exact datatype to use for comparison against the Template field.
Seeing your comment about the Image field I could suggest to try with this (NOT TESTED)
SqlParameter p = com.Parameters.Add("#Template", SqlDbType.Image);
p.Value = Template;
SqlDataReader sr = com.ExecuteReader();
This seems to be necessary because adding a value of byte[] type with AddWithValue creates automatically a SqlDbType.Binary parameter type, instead the database seems to like an SqlDbType.Image, However, read about deprecated Image field
Try this.Add parameter for #template
SqlCommand com = new SqlCommand("SELECT * FROM tblFingerprint WHERE Template = #Template)", cn);
com.Parameters.AddWithValue("#Template", Template);
I have the code below (I've included what I believe are all relevant sections):
private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_# = ?;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.Add(new MySqlParameter("", val1));
m.Parameters.Add(new MySqlParameter("", val2));
MySqlDataReader r = m.ExecuteReader();
if (r.HasRows)
level = Convert.ToInt32(r.GetValue(0).ToString());
r.Close();
return true;
}
When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
Try this instead:
private String readCommand =
"SELECT LEVEL FROM USERS WHERE VAL_1 = #param_val_1 AND VAL_2 = #param_val_2;";
public bool read(string id)
{
level = -1;
MySqlCommand m = new MySqlCommand(readCommand);
m.Parameters.AddWithValue("#param_val_1", val1);
m.Parameters.AddWithValue("#param_val_2", val2);
level = Convert.ToInt32(m.ExecuteScalar());
return true;
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
MySqlConnection con = new MySqlConnection("server=localhost;User Id=root;database=result;password=1234");
con.Open();
MySqlCommand cmd = new MySqlCommand("Select * from users where username=?username and password=?password", con);
cmd.Parameters.Add(new MySqlParameter("username", this.Login1.UserName));
cmd.Parameters.Add(new MySqlParameter("password", this.Login1.Password));
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows ==true)
{
e.Authenticated = true;
}
}
You need to use named parameters in your query. E.g.:
String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ?param1 AND VAL_2 = ?param2";
Then, pass the parameter names when you instantiate your MySqlParameter objects like so:
m.Parameters.Add(new MySqlParameter("param1", val1));
m.Parameters.AddWithValue("parameter",value)
will be better option for parametrized query.
I don't think the MySql.Data classes support unnamed parameters. If you're keen to use them, you could access your MySql db via the Odbc drivers, they support this.
You'll need to name the parameters in your query:
"SELECT LEVEL FROM USERS WHERE VAL_1 = #val1 AND VAL_2 = #val2;"
I've chosen the param indicator "#", but recent versions of MySql.Data support both "#" and "?".
Then update your param constructor to pass in the correct param name (you don't need to include the param indicator here, although it doesn't make any difference if you do).
m.Parameters.Add(new MySqlParameter("val1", val1));
PS. You prob know this already, or it was just omitted in the snippet, but I think you forgot to call Read on your instance of ExecuteReader.
If you want to execute the sql many times, then you should use this way:
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
cmd.ExecuteNonQuery();
}
First time is without "ExecuteNonQuery" just adding the parameters with faked values, then inside the loop you add the real values.
See this link:
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html