Must declare the scalar variable "#username". How to overcome it - c#

I am having problem with my code Always having the error which i am not understanding. Please help with my code
i want to retrieve the user details from the db for login page
string uname = TextBox1.Text.Trim();
string pass = TextBox2.Text.Trim();
try
{
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
Response.Write("Login successful");
}
else
{
Response.Write("login Unsucessful");
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}

You need to create your cmd prior to adding the paramaters. Your code should look like:
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
EDIT: and as #ekad said, you do not need cmd.ExecuteNonQuery();

Related

How do i update picture using sqlconnection

it always show an error Incorrect syntax near ')'.
I didnt see any wrong inputs
See my code below
byte[] content = ImageToStream(fName);
cnn.Open();
string sql = "update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id)";
SqlCommand cmd1 = new SqlCommand(sql, cnn);
cmd1.Parameters.AddWithValue("#pic", SqlDbType.Image).Value = content;
cmd1.Parameters.AddWithValue("#fname", SqlDbType.VarChar).Value = txtfirstname.Text;
cmd1.Parameters.AddWithValue("#mname", SqlDbType.VarChar).Value = textBox1.Text;
cmd1.Parameters.AddWithValue("#lname", SqlDbType.VarChar).Value = txtlastname.Text;
cmd1.Parameters.AddWithValue("#position", SqlDbType.VarChar).Value = comboBox2.Text;
cmd1.Parameters.AddWithValue("#startterm", SqlDbType.DateTime).Value = dateTimePicker2.Value.Date;
cmd1.Parameters.AddWithValue("#endterm", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
cmd1.Parameters.AddWithValue("#id", SqlDbType.Int).Value = int.Parse(ID.Text);
cmd1.ExecuteNonQuery();
cnn.Close();
MessageBox.Show("successfully updated");
dataGridView1.DataSource = db.sp_viewofficials();
it should save to sql server my save works
Your update statement has extra ending bracket which is not needed.
"update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id"

fatal error encountered during command execution in c#.net mysql

I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.

Need Id to Upload excel sheet in the gridview

I have a feature to upload the Excel sheet data into the gridview. The data will get inserted into the child table of database.
Now, My issue here is. One of the column has a relation with the Master table.
So, untill and unless I add that column ID which has a relation it gives me error as
The Student_id column was not supplied
Here is my code
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select count(email) from tbl_student_report where email=#email", con);
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = dt.Rows[i]["Email Id"].ToString();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Duplicate user in the sheet, Sheet will not be uploaded..!!!');window.location ='csrstudentprogress.aspx';", true);
continue;
}
cmd = new SqlCommand("INSERT INTO tbl_student_report(NgoId,student_id,name,email,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#NgoId,#student_id,#name,#email,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = dt.Rows[i]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = dt.Rows[i]["StudentId"].ToString();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
Please suggest what to do in this case, because User will not add student_id in the excel sheet and upload.
I am using sql-server 2008
How to achieve this ??
I got it done by trying myself like below:-
Helper class
public static DataTable GetUserIdByName(string userName,string userType)
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_User WHERE Username=#Username AND UserType=#UserType", con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("#UserType", SqlDbType.VarChar).Value = userType;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
}
And calling the Class in the Export function did the job:-
DataTable table = GeneralHelper.GetUserIdByName(Session["User"].ToString(), Session["UserType"].ToString());
for (int i = 0; i < dt.Rows.Count; i++)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
if (table != null && table.Rows.Count > 0)
{
string StudentId = GetNgoIdStudentId(dt.Rows[i]["Email Id"].ToString());
if (StudentId != null)
{
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_student_report(student_id,name,emailid,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#student_id,#name,#emailid,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = table.Rows[0]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = StudentId;
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#emailid", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
if (string.IsNullOrEmpty(dt.Rows[i]["Date Of Record"].ToString()))
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
}
if (string.IsNullOrEmpty(dt.Rows[i]["Modified Date"].ToString()))
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
}
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Student not found');", true);
}
}
else
{
//Error
}
}
}

username is not correct error i dont even know y please someone help me

I keep getting a username is incorrect error this is for login i dont know why i desperatley need help, i did everything correct but still gives me errors what can i do
below is my code
protected void Button_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where UserName=#UserName";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value = TextBoxUserName.Text + "'";
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
//int temp = Convert.ToInt32(com.ExecuteScalar());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPasswordQuery = " select password from [Table] where UserName=#UserName";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
passComm.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = TextBoxUserName.Text;
string password = passComm.ExecuteScalar().ToString().Replace(" ", "");
if (password == TextBoxPassword.Text)
{
//declaring new session
Session["New"] = TextBoxUserName.Text;
Response.Write("PASSWORD IS CORRECT");
Response.Redirect("Default.aspx");
}
else
{
Response.Write("PASSWORD IS NOT CORRECT");
}
}
else
{
Response.Write("USERNAME IS NOT CORRECT");
}
}
You don't need to add single quote at the end of the username.
Replace This:
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value =
TextBoxUserName.Text + "'";
^^^^^^
With This:
com.Parameters.Add("#UserName", SqlDbType.NChar, 20).Value = TextBoxUserName.Text;
You should also trim your parameters in both queries.
string checkPasswordQuery = " select password from [Table] where Ltrim(Rtrim(UserName))=#UserName";
SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
passComm.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = TextBoxUserName.Text.Trim();
Your SQL query is case-sensitive, which may or may not be intended.
You believe you can use
"select count(*) from [Table] where Lower(UserName)=Lower(#UserName)"
MDSN Link: http://msdn.microsoft.com/en-us/library/ms174400.aspx

c# ado.net sqlparameter fails

I am passing sqlparameter in localize language (Persian) from c# but no rows retrieves. Database already collate for persioan_100_ci_ai and tables are collate database_default
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]=#UserName AND [Pwd]=#Password";
cmd.commandtext = qry;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = "ادمین";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = "ادمین";
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
It works in SSMS
declare #UserName nvarchar(50) = 'ادمين'
declare #Password nvarchar(50)= 'ادمين'
select * from Users where [name]=#UserName and [Pwd] = #Password
It even works when I am embedding variables in query instead of parameter
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
SqlDataReader dr = default(SqlDataReader);
string pLoginName = "ادمین";
string pPassword = "ادمین";
dt.TableName = "temp";
try {
if (!(conn.State == ConnectionState.Closed))
conn.Close();
if (conn.State == ConnectionState.Closed)
conn.Open();
cmd.Connection = conn;
string qry = "Select * from users WHERE [Name]='" + pLoginName + "' AND [Pwd]='" + pPassword + "'";
cmd.CommandText = qry;
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows) {
dt.Load(dr);
}
return dt;
} catch (Exception ex) {
return null;
} finally {
dt = null;
cmd.Connection = null;
cmd.Parameters.Clear();
cmd.Dispose();
}
Cannot figure out where I am wrong.
Please, if any one can point out.
I don't have any problems, I add both values to my test database. Here is the sample code
// Code in BO logic method
string email = "ادمین";
string password = "ادمین";
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Register WHERE Email=#Email AND Deleted=0 AND Password=#Pass");
cmd.Parameters.AddWithValue(#"Email", email.Trim());
cmd.Parameters.AddWithValue(#"Pass", password.Trim());
DataSet dst = Varmebaronen.AppCode.DA.SqlManager.GetDataSet(cmd);
//DataAccess Methods !
public static DataSet GetDataSet(SqlCommand cmd)
{
return GetDataSet(cmd, "Table");
}
public static DataSet GetDataSet(SqlCommand cmd, string defaultTable)
{
SqlConnection conn = GetSqlConnection(cmd);
try
{
DataSet resultDst = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(resultDst, defaultTable);
}
return resultDst;
}
catch
{
throw;
}
finally
{
conn.Close();
}
}
DataSet had one record, try to use AddWithValue. If again nothing happen the problem is not in the parameters !
P.S Don't use one static connection, application pool is your friend !
Try seperating out the parameter and value assignment like below:
// Create the parameter objects as specific as possible.
cmd.Parameters.Add("#UserName", System.Data.SqlDbType.NVarChar, 50);
cmd.Parameters.Add("#Password", System.Data.SqlDbType.NVarChar, 50);
// Add the parameter values. Validation should have already happened.
cmd.Parameters["#UserName"].Value = "ادمین";
cmd.Parameters["#Password"].Value = "ادمین";
Try to use this:
cmd.Parameters.Add(new SqlParameter("#Password", "ادمین"));
EDIT:
Lets try a different way. If you're up for some re-coding. I will post an example from an old college project that works. It's essentially the same concept. May not be the best way but it works...
I used a DataAdapter, a DataSet, and a GridView control on an .aspx page. You tagged ASP.net, but I am not sure what you're trying to use to display the data.
string selectsql2 = "SELECT * FROM [dbo].Event_View WHERE (EventName LIKE '%' + #EventName + '%')";
SqlConnection connect2 = new SqlConnection(connectionstring2);
SqlCommand cmd = new SqlCommand(selectsql2, connect2);
SqlParameter pm = new SqlParameter("#EventName", txtEvents.Text);
cmd.Parameters.Add(pm);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
gvEvents.DataSource = ds2;
gvEvents.DataBind();

Categories

Resources