Row Deletion ADO.Net, ASP.Net - c#

I am trying to work with a contact list and want to remove all of the info on a person when I type in their name. I am using a sql table -named Contact- that contains the Name, Email and Address of a contact. I have the following code:
protected void Delete_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnect"].ConnectionString);
con.Open();
string delete = "DELETE FROM Contact WHERE Name =" + NameToDelete.Text;
SqlCommand cmd = new SqlCommand(delete, con);
try
{
cmd.Parameters.AddWithValue("#Name", delete);
cmd.ExecuteNonQuery();
Response.Redirect("ViewContacts.aspx");
}
catch(Exception ex)
{
Response.Write(ex);
}
}
When I use this, it seems to be comparing the column Name to the name I am putting in. So the name Bill is being compared against the column header Name instead of what is in the name.

You need to use single quotes around the values with var(char) types. If you don't use quotes it will think that you are referencing a column name instead of value.
It's valid for all databases, following is from oracle docs:
character literals are enclosed in single quotation marks, which
enable Oracle to distinguish them from schema object names.
https://docs.oracle.com/cd/A87860_01/doc/server.817/a85397/sql_elem.htm
string delete = "DELETE FROM Contact WHERE Name ='" + NameToDelete.Text + "'";
Actually what you are trying to do is using sqlcommand parameter, then you need to use parameter name using #[ParameterName] in sql statement.
string delete = "DELETE FROM Contact WHERE Name = #Name";

Seems that your problem is that you are using the variable delete in two instances. First for create the command that is fine and second as the parameter value, which is wrong. In the parameter value probably you must use the value tthat you want to delete.

You have several serious problems with your code.
Your connection is never closed or disposed. Use Using blocks which will close and dispose of database objects even if there is an error.
You are concatenating a string to get your Sql statement risking Sql injection and damage to your database.
You are adding a parameter to your command when there are no parameters in your Sql statement.
You are using .AddWithValue which takes the parameter name and the parameter value as arguments. You have provided your entire Sql statement as the value of #Name. This should be NameToDelete.Text.
Do not use .AddWithValue. Use .Add(parameter Name, Sql data type).Value = value of parameter. This can speed up queries and avoids type mismatches in the database.
If name is your Primary Key, you are OK, but if not you should delete by the primary key or send all values in the Where clause.
protected void Delete_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnect"].ConnectionString))
{
string delete = "DELETE FROM Contact WHERE Name = #Name;"; //no single quotes to worry about
using (SqlCommand cmd = new SqlCommand(delete, con))
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = NameToDelete.Text; //just guessed at the VarChar - check your database for type
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("ViewContacts.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message); //ex by itself, will get you nothing but the fully qualified name of Exception
}
}
}
}

Related

I am trying to save inputs using combo boxes and a date time picker to a ms access database and it says : Data type mismatch in criteria Expression

private void button2_Click(object sender, EventArgs e)
{
try
{
using (var con = new OleDbConnection())
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ZwaneZP01\source\repos\HenleyFaultsSystemSbu\Faults.accdb;";
con.Open();
using (var com = new OleDbCommand())
{
com.Connection = con;
com.CommandText = "INSERT INTO Faults ([Date],[Job],[Area],[ReportedBy],[ReportedTo],[Equipment],[Workshop]," +
"[SerialNo],[Delay],[TimeSpent],[FANo],[Category],[Fault],[Action],[Status]) " +
"VALUES (#Date,#Job,#Area,#ReportedBy,#ReportedTo,#Workshop,#Equipment,#Fault,#Action,#Delay,#TimeSpent,#Status,#SerialNo,#FANo,#Category)";
com.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
com.Parameters.AddWithValue("#Job", comboBox1.Text);
com.Parameters.AddWithValue("#Area", AreacomboBox2.Text);
com.Parameters.AddWithValue("#ReportedBy", NameCodeReportedBy.Text);
com.Parameters.AddWithValue("#ReportedTo", ReportedToBox.Text);
com.Parameters.AddWithValue("#Workshop", WorkshopBox.Text);
com.Parameters.AddWithValue("#Equipment", EquipmentBox.Text);
com.Parameters.AddWithValue("#Fault", textBox2.Text);
com.Parameters.AddWithValue("#Action", textBox3.Text);
com.Parameters.AddWithValue("#Delay", DelayBox.Text);
com.Parameters.AddWithValue("#TimeSpent", TimeBox.Text);
com.Parameters.AddWithValue("#Status", checkBox1.Checked);
com.Parameters.AddWithValue("#SerialNo", textBox4.Text);
com.Parameters.AddWithValue("#FANo", textBox5.Text);
com.Parameters.AddWithValue("#Category", CategoryComboBox.Text);
com.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
}
catch (Exception ex)
{
MessageBox.Show("Not saved: " + ex.Message);
}
}
//So this is not saving to the database
I tried changing the date format as I thought its probably the date but that has not helped either
I expect it to save to the data but I am getting an error about criteria mismatch
The first thing to fix is removing all those AddWithValue and replacing them with
com.Parameters.Add("#Date", OleDbType.DateTime).Value = dateTimePicker1.DateTime;
and so on...
This is important because AddWithValue is not able to pass a parameter of type DateTime as expected by your database table if you give it a string of text. You should alwasy be
precise when providing parameters to your underlying database (MS-Access or not)
But then there is another problem. The OleDb library is not able to recognize the parameters by their names and assign the value to the correct place in your sql.
OleDb pass the parameters values looking at their position in the collection so the parameter #Workshop is assigned to the Equipment field and viceversa the parameter #Equipment is assigned to the Workshop field.
You should arrange your parameter list following the exact order in which the parameter placeholders appears in the sql text and, of course, verify that every parameter placeholder matches the corresponding field to update

Updating Table in asp.net

protected void Button1_Click(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
{
int Id = Convert.ToInt32(Request.QueryString["Id"]);
String fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Order/" + fileName));
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ToString());
con.Open();
String Update =("Update Order set DesignedImage=#DesignedImage where Id=#Id");
SqlCommand cmd = new SqlCommand( Update , con);
cmd.Parameters.AddWithValue("#DesignedImage", "Order/" + fileName);
cmd.Parameters.AddWithValue("#Id", + Id);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "OK";
}
I want to update table Order.
this code is giving me syntax error near keyword Order
Order is a reserved keyword in T-SQL. You need use it with square brackets as [Order].
As a best practice, change it to non-reserved word.
It would be better to use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
Also don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type (SqlDbType) and it's size.
As a last thing, Open your connection just before you execute your command.
You cannot have Order as your table name since it is reserved keyword on sql queries.
Rename the table and try.

How to pass table name as parameter in OleDB?

private void button1_Click(object sender, EventArgs e)
{
string tablename = label2.Text;
string name = TextBox1.Text;
DBconnection.savetodb(tablename, name);
}
I call the method below from another form to save the name into a specific table. But it wont save into my table in database.
public static void savetodb(string tablename, string name)
{
OleDbConnection connection = GetConnection();
string query = String.Format("INSERT INTO {0} (Name) VALUES (#Name)", tablename);
OleDbCommand cmd = new OleDbCommand(query, connection);
cmd.Parameters.AddWithValue("#Name", name);
try{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex){
Console.WriteLine("Exception catch", ex);
}
finally{
myConnection.Close();
}
Thanks for help.
You are not passing table name as a parameter, you are passing your #Name value as a parameter. You can't pass a table name as a parameter even if you want. Parameters only for values, not table or column names. You are just formatting your query based table name. As far as I see, your problem using named parameters. OleDb provider does not support named parameters.
From OleDbCommand.Parameters
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Try it as;
string query = String.Format("INSERT INTO {0} (Name) VALUES (?)", tablename);
...
cmd.Parameters.AddWithValue("#name", name);
Also use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection connection = new GetConnection())
using(OleDbCommand cmd = con.CreateCommand())
{
}
And consider to use .Add method instead .AddWithValue. It may cause some problems. Read Can we stop using AddWithValue() already?

No value given for one or more required parameters while trying to add a record

I am trying to add a new record into a table of the database, based on textbox input. However, I am getting an error:
No value given for one or more required parameters
I have this code:
private void addWord_Click(object sender, EventArgs e)
{
try
{
using (OleDbConnection conn = new OleDbConnection(access7ConnectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO Words VALUES(" + "#Name)", conn))
{
cmd.Parameters.AddWithValue("#Name", Word.Text);
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.ToString());
}
}
From what I read, ID does not need to be defined if the table's primary key is being auto-incremented. So here is the table in question in Access.
If I give it the ID parameter, it throws up an error that it cannot allow duplicates. How do I fix this?
Try this for your query
"INSERT INTO Words (Word) VALUES(?)"
This would specifically indicate field to insert into and question mark is a placeholder for parameters when dealing with OleDB connection.

SQL Query issues: invalid identifier

I've been working on a delete function for a while now, and I cannot get past this error.
Delete Failed ORA-00904 "SYSTEM"."DATA"."DATAROWVIEW": invalid identifier
private void button3_Click(object sender, EventArgs e)
{
string yesNoPrompt = "Are you sure you want to delete this patient?";
const string caption = "";
var result = MessageBox.Show(yesNoPrompt, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
string sql = "DELETE FROM CLIENT WHERE (CLI_LNAME =" + listBox1.SelectedItem.ToString() + ")" ;
try
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = new OracleCommand(sql, connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
catch (System.Data.OracleClient.OracleException ex)
{
MessageBox.Show("Delete Failed" + ex.Message);
}
}
}
The table in the database is CLIENT and I am trying to find a specific person by their last name, or CLI_LNAME. I don't think the problem is in the name being passed, but more of how it is being passed.
Any ideas?
Your query gets translated to
DELETE FROM CLIENT WHERE (CLI_LNAME = SYSTEM.DATA.DATAROWVIEW)
Due to the missing single quotes and hence its trying to find a column named SYSTEM.DATA.DATAROWVIEW which is not present in the Client table. hence the error.
When you use single quotes then its looking for the text in that particular column
DELETE FROM CLIENT WHERE (CLI_LNAME = 'PatientName') // Now its not a column as such
Use Parameterized queries to avoid SQL injection
Looks like listBox1.SelectedItem.ToString() returns "SYSTEM"."DATA"."DATAROWVIEW". You probably want to access a specific item of the DataRowView that's the SelectedItem, not the entire DataRowView object itself. Maybe listBox1.SelectedItem[0].ToString() is what you want?.
Also you have to add quotes as #Habib.OSU mentions.
And the obligatory sql injection warning: Don't concatenate user inputs into SQL string. It opens up for SQL injection attacks. Use parameterized queries.
you are missing single quote in parameters
string sql = "DELETE FROM CLIENT WHERE (CLI_LNAME ='" + listBox1.SelectedItem.ToString() + "')" ;
Its better if you could use Parameterized query

Categories