Parameter #un must be defined - c#

I'm getting this error
"MySql.Data.MySqlClient.MySqlException: 'Fatal error encountered
during command execution.", "MySqlException: Parameter '#un' must be
defined."
and I don't know what to do honestly I'm just following what my friend is doing and I'm just a complete newbie in coding. Here is my code.
private void BTNDELETE_Click(object sender, EventArgs e)
{
var c = cmd.Parameters;
con.ConnectionString = Properties.Settings.Default.sampledb_it11ConnectionString;
con.Open();
cmd.Connection = con;
cmd = new MySqlCommand("delete tbl_user set username=#un, password=#pw, usertype=#ut, loginname=#ln where username=#un,", con);
c.Clear();
c.AddWithValue("#un", TXTUN.Text);
c.AddWithValue("#pw", TXTPW.Text);
c.AddWithValue("#ut", CBOUT.Text);
c.AddWithValue("#ln", TXTLN.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been deleted", "Deleting Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
TXTUN.Text = "";
TXTPW.Text = "";
TXTCPW.Text = "";
TXTLN.Text = "";
CBOUT.Text = "";
TXTUN.Focus();
DG_Refresh();
TXTUN.Enabled = true;
}

The error or "MySqlException: Parameter '#un' must be defined." is caused by undefined parameters of the MySqlCommand object. It is incorrect to store the parameters in 'c':
var c = cmd.Parameters;
c.AddWithValue("#un", TXTUN.Text);
I would suggest you revise it to :
cmd.Parameters.AddWithValue("#un", TXTUN.Text);
Additionally, the sql scripts are messed up. From the MessageBox and the name of button, it seems you mean to delete a row in the database. So the script should be:
cmd = new MySqlCommand("delete tbl_user where username=#un,", con);
Looks like what your friend do is to update a row while you are going to delete a row. The keyword 'set' should be paired with 'update' command.
And it is incorrect to create a new instance of MySqlCommand after assigning the connection.
cmd.Connection = con;
cmd = new MySqlCommand...
Finally, the code statements would be like this:
con.ConnectionString = Properties.Settings.Default.sampledb_it11ConnectionString;
con.Open();
MySqlCommand cmd = new MySqlCommand("delete tbl_user where username=#un,", con);
cmd.Connection = con;
cmd.Parameters.AddWithValue("#un", TXTUN.Text);
cmd.ExecuteNonQuery();
con.Close();

Related

Syntax error in UPDATE statement while updating password in Access database

I faced syntax error in UPDATE statement, while updating password in Access database in C#:
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE into userdata(password)values('"+TextBox1.Text+"') where id=#id";
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
}
It's because your SQL Query is not correct, that's not how you update data in your database. It should be like this:
query = "Update [tableName] SET [ColumnName] = 'Values', [ColumnName1] = 'Values2',...";
You should learn at least the basics of SQL syntax, more information here
And also, you shouldn't concatenate your query since it will become vulnerable for SQL Injection attack, you should at least use Parameterized Query
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
Server.MapPath("~/Database/registration.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"UPDATE yourTableName SET [yourColumnName] = #YourFirstValue, [secondColumnName] = #YourSecondValue WHERE [columnKey] = #ID"
cmd.Parameters.AddWithValue("#YourFirstValues", textbox1.Text);
cmd.Parameters.AddWithValue("#YourSecondValue ", textbox2.Text);
cmd.Parameters.AddWithValue("#ID", textbox3.Text);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("alert('Password Reset Successfully done');");
you have to fix your query
"UPDATE userdata SET password=#password where id=#id";
and add new lines before cmd.ExecuteNonQuery()
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#password", TextBox1.Text);
I had a similar problem, it gave me a syntax error that I solved by checking the whole string and actually there was a comma too many, I don't know if this answer of mine can be useful, among other things after some time.

The parameterized query expects parameter xy which was not supplied

I'm trying to do an app without adding some details about a car delivery.
I wrote the code in C# and SQL, but when I add the data to textbox, radiobutton, labels, etc. I get this error:
System.Data.SqlClient.SqlException: 'The parameterized query '(#a int,#b nvarchar(7),#c int,#d nvarchar(12),#e nvarchar(10),#f' expects the parameter '#f', which was not supplied.'
But I tried by debug to see if they take values and all have values less #f
The length of the columns in the database is 50 or 100
if (materialRadioButton5.Checked)
{
choose = "Excelent";
}
else if (materialRadioButton8.Checked)
{
choose = "Foarte bună";
}
else if (materialRadioButton7.Checked)
{
choose = "Bună";
}
else if (materialRadioButton6.Checked)
{
choose = "Uzată";
}
if (materialRadioButton4.Checked)
{
chooser = "Mulţumit";
}
else if (materialRadioButton1.Checked)
{
chooser = "Nemulţumit";
}
SqlConnection con = new SqlConnection(stringcon);
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.CommandText = "insert into returncar(id_client,fullname_client,id_team,fullname_team,rendition,condition,team_mention,customers_plesed,exp_felt,client_mention) values(#a,#b,#c,#d,#e,#f,#g,#h,#i,#j)";
cmd.Parameters.AddWithValue("#a", Convert.ToInt32(label65.Text));
cmd.Parameters.AddWithValue("#b", label67.Text);
cmd.Parameters.AddWithValue("#c", Convert.ToInt32(label66.Text));
cmd.Parameters.AddWithValue("#d", label68.Text);
cmd.Parameters.AddWithValue("#e", metroDateTime1.Text);
cmd.Parameters.AddWithValue("#f", choose);
cmd.Parameters.AddWithValue("#g", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#h", chooser);
cmd.Parameters.AddWithValue("#i", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#j", materialSingleLineTextField1.Text);
cmd.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = con;
cmd2.Parameters.Clear();
cmd2.CommandText = "update rentcar set inchiriat=0 where id=#id";
cmd2.Parameters.AddWithValue("#id", Form2.idddloan);
cmd2.ExecuteNonQuery();
con.Close();
panel2.Visible = false;
bunifuFlatButton7.Visible = false;
How radiobutton4 and radiobutton1 works and the others do not?...
public string choose, chooser;
If the value is null then the parameter is not added and you'll get the exception you mentioned. In these cases make sure to check for null and instead pass
choose ?? Value.DBNull

object reference not set to an instance of an object, sql query not runnable?

I'm pretty sure that the Sql Syntax is right since it's a legit query.
However i've never stumbled on this issue before.
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
{ MessageBox.Show(ex.Message); }
}
}
The problem may be related to this:
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
try
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
cmd.ExecuteNonQuery
MessageBox.Show("Användaren borttagen.");
}
Now you've shown us your whole code in the comments, the problem is obvious.
You have written a method to initialise, set up and open your database connection; and this other method which runs on a button click, which uses it.
However, nowhere in your code do you call the method which initialises your database connection, therefore it is not set up when you try to use it - obvious really.
I can see you think you are checking to see if the connection is working by checking its State property, but calling any sort of method or property accessor on an uninitialised reference type won't work, you'll get the NullReferenceException you've been getting.
To fix, call the connection set up method from your button press, before trying to use the connection:
private void button1_Click(object sender, EventArgs e)
{
string ett = textBox1.Text;
if (ett == "")
{
MessageBox.Show("Du måste fylla i UID, vilket du finner i användarlistan.");
return;
}
try
{
db_connection(); //added this line
if (connect.State == ConnectionState.Open)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.CommandText = "DELETE FROM Users WHERE uid = #uid";
cmd.Parameters.AddWithValue("#uid", textBox1.Text);
MySqlDataReader accessed = cmd.ExecuteReader();
MessageBox.Show("Användaren borttagen.");
}
else
{
MessageBox.Show("Något gick tyvärr fel, kontakta systemadministratören.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have not defined the variable, "connect".

How to insert data into a database table using a SqlCommand

I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.

how can I generalize my code to rename column names via asp.net

I create a web form that contains: Dropdownlist, texbox and rename button.
The general idea is that Dropdownlist contains list of column names of one table in my database.
Then the user select one of these names and enter the new name in the textbox. After that, he click the rename button. The result is rename the selected column in my database.
My code is work well. And it is give exact result.
see my code:
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Data Source=FATTO-TOSH\SQLEXPRESS;Initial Catalog=Positions;Integrated Security=True";
if (DropDownList1.SelectedIndex == 0)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill1")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
if (DropDownList1.SelectedIndex == 1)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill2")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
if (DropDownList1.SelectedIndex == 2)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill3")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
}
My question is:
The modification achieved only one time (regard to one column) because when I change the name from skill1 to Sk for example. May in other time, the user want to modify Sk to other name. the code doesn't work because it is initialize as column name is skill1 only. do you have an idea how to generalize the code to work whatever the name of the column?
thank you
Instead of using DropDownList1.SelectedIndex why don't you have the name of the column you want it to be changed to listed in the DropDownList1 and then use DropDownList1.SelectedValue like so:
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Data Source=FATTO-TOSH\SQLEXPRESS;Initial Catalog=Positions;Integrated Security=True";
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", DropDownList1.SelectedValue)
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
}
MSDN
Make sure you toss in some null checking on the SelectedValue before you actually execute any commands.

Categories