Delete a row from a SQL Server table - c#

I'm trying to simply delete a full row from my SQL Server database table using a button event. So far none of my attempts have succeeded. This is what I'm trying to do:
public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + IDNumber, con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}
I keep receiving the error:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
An error occurred: Operand type clash: text is incompatible with int
All of the columns in the table are of TEXT type. Why cannot I compare the function argument of type string to the columns to find the match? (And then delete the row?)

As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around IDNumber.....
public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}

Either IDNumber should be an int instead of a string, or if it's really a string, add quotes.
Better yet, use parameters.

Try with paramter
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + #IDNumber, con))
{
command.Paramter.Add("#IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
No need to close connection in using statement

Looks like IDNumber is a string. It needs single quote wrapped around it.
"DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber + "'"

You may change the "columnName" type from TEXT to VARCHAR(MAX). TEXT column can't be used with "=".
see this topic

private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("delete successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM suppliers";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
SqlDataReader reader = sqlcom.ExecuteReader();
DataTable datatable = new DataTable();
datatable.Load(reader);
dataGridView1.DataSource = datatable;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

If you are using MySql Wamp. This code work.
string con="SERVER=localhost; user id=root; password=; database=dbname";
public void delete()
{
try
{
MySqlConnection connect = new MySqlConnection(con);
MySqlDataAdapter da = new MySqlDataAdapter();
connect.Open();
da.DeleteCommand = new MySqlCommand("DELETE FROM table WHERE ID='" + ID.Text + "'", connect);
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Deleted");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}

private void DeleteProductButton_Click(object sender, EventArgs e)
{
string ProductID = deleteProductButton.Text;
if (string.IsNullOrEmpty(ProductID))
{
MessageBox.Show("Please enter valid ProductID");
deleteProductButton.Focus();
}
try
{
string SelectDelete = "Delete from Products where ProductID=" + deleteProductButton.Text;
SqlCommand command = new SqlCommand(SelectDelete, Conn);
command.CommandType = CommandType.Text;
command.CommandTimeout = 15;
DialogResult comfirmDelete = MessageBox.Show("Are you sure you want to delete this record?");
if (comfirmDelete == DialogResult.No)
{
return;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}

Related

How to fix input string was not in a correct format in sql on C#?

public static String AccountNumber;
public static double oldBalance, newBalance;
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\CSharp\ATM\DB\LoginDB.mdf;Integrated Security=True;Connect Timeout=30");
private void iconButton1_Click(object sender, EventArgs e)
{
newBalance = oldBalance + Convert.ToInt32(txtAmmount.Text);
try
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.SelectCommand = new SqlCommand("UPDATE Account SET AccBalance ='" + Convert.ToDouble(newBalance) + "'WHERE AccountNum =" + txtAccount.Text.Trim() + "", connection);
DataTable data = new DataTable();
adapter.Fill(data);
if (data.Rows.Count >0)
{
MessageBox.Show("Deposit Success", "Deposit", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Deposit Faild", "Deposit", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(" " + ex, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void GetBalance()
{
try
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
AccountNumber =Form1.AccountNumber;
int accounts=Convert.ToInt32(AccountNumber);
adapter.SelectCommand = new SqlCommand("SELECT AccBalance FROM Account WHERE AccountNum='" + accounts + "'", connection);
DataTable data = new DataTable();
adapter.Fill(data);
oldBalance = Convert.ToInt32(data.Rows[0][0].ToString());
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Warning Message!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void Form3_Load(object sender, EventArgs e)
{
GetBalance();
}
When I load the Form, I get an error
Input string was not in a correct format
I think the error is here
UPDATE Account SET AccBalance ='" + Convert.ToDouble(newBalance) + "'WHERE AccountNum =" + txtAccount.Text.Trim() + ""
In the runtime, for example, newBalance = 1 and then txtAccount.Text = "My name" the result will be
UPDATE Account SET AccBalance ='1'WHERE AccountNum =My Name
As you can see:
No space between 1' and WHERE
No ' before and after "My Name"
That's why the code can't work and now you know how to fix it.
As some comment already above, you should use SQLCommand Params instead of building raw SQL string https://csharp-station.com/Tutorial/AdoDotNet/Lesson06

The error says "The ConnectionString property has not been initialized" in c#

this code is for the combo box where i want to select some index to show it to my textboxes.
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//My program is completely running but not in this section. :(
Is you made an connection between your application and database source using conn object ? You might be used conn object as a connection object but before this was you initialized you Connection ?
Simpy use like
"SqlConnection conn=new SqlConnection("Connection_Source");"
here is your error.
You have to define the connection string for the connection, here i suggest you one best method for executing command.
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
If its just to select value from comboBox and display in textBox , then below code will help you...
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}

“Data type mismatch in criteria expression” error in C# when I click on save button

private void button1_Click(object sender, EventArgs e)
{
try
{
string strcmd = "INSERT INTO student VALUES('" + txtsname.Text + "','" + txtsrollno.Text + "')";
cmd = new OleDbCommand(strcmd, MyConn);
if (MyConn.State == ConnectionState.Closed) { MyConn.Open(); }
cmd.ExecuteNonQuery();
if (MyConn.State == ConnectionState.Open) { MyConn.Close(); }
showData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Looks like Roll No is of integer type and you are trying to insert string data by enclosing value in single quotes.
Use Parameters. They will save you from SQL Injection and will prevent errors like the above. You can do something like:
private void button1_Click(object sender, EventArgs e)
{
try
{
string strcmd = "INSERT INTO student VALUES(#name,#rollno)";
using (OleDbConnection MyConn = new OleDbConnection("connectionstring"))
{
using (OleDbCommand cmd = new OleDbCommand(strcmd, MyConn))
{
cmd.Parameters.AddWithValue("#name", txtsname.Text);
cmd.Parameters.AddWithValue("#rollno", int.Parse(txtslrollno.Text));
if (MyConn.State == ConnectionState.Closed) { MyConn.Open(); }
cmd.ExecuteNonQuery();
if (MyConn.State == ConnectionState.Open) { MyConn.Close(); }
showData();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
this error is due to may be your table columns for name and roll number have different type. In code you are passing text so in database these columns should have varchar data type.
i suspect you have more columns in table and in program you are passing only two values now sql is consdiering that you have only two columns in your table to fix it you need to rewrite your sql query. i am using dummy column name please change it to your own columns.
private void button1_Click(object sender, EventArgs e)
{
try
{
string strcmd = "INSERT INTO student (name, rollno) VALUES('" + txtsname.Text + "','" + Convert.ToInt32(txtsrollno.Text) + "')";
cmd = new OleDbCommand(strcmd, MyConn);
if (MyConn.State == ConnectionState.Closed) { MyConn.Open(); }
cmd.ExecuteNonQuery();
if (MyConn.State == ConnectionState.Open) { MyConn.Close(); }
showData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

C# SQL Server CE - Update won't work

I'm trying to finish a college project that requires a program to interact with a database.
Some of my naming is a little odd, but don't worry!
I'm trying to use a single submit button to either update or insert to the database.
Main issue is that I can't get an update to work though when I changed my code to try and fix it, I made it worse. Here is what I currently have.
private void btn_submit_Click(object sender, EventArgs e)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT TaskCode FROM TaskCode;";
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
SqlCeDataReader reader;
reader = c1.ExecuteReader();
if (reader.Read())
{
try
{
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, TaskDescription = #TaskDescription = WHERE TaskCode = #TaskCode;";
SqlCeCommand c = new SqlCeCommand(taskUpdate, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been updated");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
else
{
try
{
string taskInsert = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
SqlCeCommand c = new SqlCeCommand(taskInsert, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
}
}
Has anyone got any ideas why I am getting an error on the c.ExecuteQuery line?
If I remove said line, it will not throw an exception, but it will not update the database.
Thanks
You have a simple syntax error in your update query just before the where statement.
There is an invalid equal sign
string taskUpdate = "UPDATE TaskCode SET TaskCode = #TaskCode, " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
Your query also could be simplified with
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=G:\Dropbox\HND\Visual Studio\Visual C#\TestForms\TestForms\Database1.sdf"))
{
con.Open();
string taskSel = "SELECT COUNT(*) FROM TaskCode";
string cmdText;
SqlCeCommand c1 = new SqlCeCommand(taskSel, con);
int count = (int)c1.ExecuteScalar();
if (count > 0)
{
// Here there is no point to update the TaskCode. You already know the value
// Unless you have a different value, but then you need another parameter
// the 'old' TaskCode.....
cmdText = "UPDATE TaskCode SET " +
"TaskDescription = #TaskDescription " +
"WHERE TaskCode = #TaskCode;";
}
else
{
cmdText = "INSERT INTO TaskCode VALUES (#TaskCode, #TaskDescription);";
}
try
{
SqlCeCommand c = new SqlCeCommand(cmdText, con);
c.Parameters.AddWithValue("#TaskCode", cbx_taskCode.Text);
c.Parameters.AddWithValue("#TaskDescription", txt_desc.Text);
c.ExecuteNonQuery();
MessageBox.Show(count > 0 ? "Record has been updated" : "Record has been added");
MainMenu.Current.Show();
this.Close();
}
catch (SqlCeException exp)
{
MessageBox.Show(exp.ToString());
}
}
Not sure if it is the only problem, but you have an equal (=) sign before the WHERE keyword.

How to use UPDATE in ado net

I need to perform an update in a table(Homework). But it is not just replacing an old value with a new one; to the already existing value in the column i have to add(SUM) the new value(the column is of type int).
This is what i did so far but i am stuck:
protected void subscribeButton_Click(object sender, EventArgs e)
{
string txtStudent = (selectedStudentLabel.Text.Split(' '))[0];
int studentIndex = 0;
studentIndex = Convert.ToInt32(txtStudent.Trim());
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Trusted_Connection=True;User Instance=yes");
conn.Open();
string sql2 = "UPDATE student SET moneyspent = " + ?????? + " WHERE id=" + studentIndex + ";";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
try
{
conn.Open();
myCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
finally
{
conn.Close();
}
}
What should i add intead of ??? to achieve my goal?
Is it possible to do it this way? I want to avoid using to many queries.
If i understand you correctly (i'm not sure i do) you want something like this:
string sql2 = "UPDATE student SET moneyspent = moneyspent + #spent WHERE id=#id";
SqlCommand myCommand2 = new SqlCommand(sql2, conn);
myCommand2.Parameters.AddWithValue("#spent", 50 )
myCommand2.Parameters.AddWithValue("#id", 1 )
Notice how i've used parameters and not string concatenation, very important!!

Categories

Resources