Mass update mysql table - c#

I have a list of 1933 user names that have to be set to deleted in a mysql table (change the deleted field from 0 to 1). I'm pasting a comma delimited list (username, realname) in a list box and using a foreach statement to send each username, realname group to an update command in a static class. When I run it, I don't get any errors but none of the users rows are updated. I'm doing something wrong but I'm not sure what the issue is. Please review my code below and let me know if you find something wrong that I'm not seeing.
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
try
{
if (listBox1.Items.Count > 0)
{
foreach (string s in listBox1.Items)
{
Cursor.Current = Cursors.WaitCursor;
string[] sname = s.Split(',');
Data.RemoveUser(sname[0].ToString(), sname[1].ToString());
i++;
label3.Text = i.ToString();
}
}
else
MessageBox.Show("No user names found. Please paste a list of names to be deleted.");
Cursor.Current = Cursors.Default;
MessageBox.Show(i.ToString() + " users set to deleted.");
}
catch (Exception ex)
{
throw ex;
}
}
public static void RemoveUser(string UserName, string FullName)
{
MySqlConnection conn = new MySqlConnection(constr);
try
{
conn.Open();
string qry = "Update host_user set deleted = 1 where username = #username and name = #fname";
MySqlCommand cmd = new MySqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#username", UserName);
cmd.Parameters.AddWithValue("#fname", FullName);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (MySqlException e)
{
if (conn != null) conn.Close();
throw e;
}
}

When you are doing:
string[] sname = s.Split(',');
Do you end up with spaces on either side of you first name and last name? If your input was like:
"John, Doe"
You would end up search on "John" & " Doe".
If this is the case, call .Trim() on those strings before passing passing them into RemoveUser().

Related

How to insert data into two SQL Server tables in asp.net

I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!

Check for existing value when adding to Access

I have an interface in which one of my functions include deleting a Serial Number from Access. If the Serial Number does exist then it deletes everything as it is supposed to with a confirmation message. The problem is, I can type in a Serial Number that does not exist and it acts like it is deleting it anyway. How do I check to see if the value exists when clicking the delete button, so I can then throw a notification to the user ?
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtSerial.Text))
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string deleteEntry = "delete from Inventory where SerialNumber='" + txtSerial.Text + "' ";
DialogResult result = MessageBox.Show("ARE YOU SURE YOU WANT TO DELETE SERIAL NUMBER = " + txtSerial.Text + " ? ", "LAST CHANCE !", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result.Equals(DialogResult.OK))
{
command.CommandText = deleteEntry;
command.ExecuteNonQuery();
MessageBox.Show("Data Has Been Deleted".PadLeft(28));
}
if (dataGridFB.DataSource != null)
{
dataGridFB.DataSource = null;
txtSerial.Clear();
comboSerial.Text = string.Empty;
comboPart.Text = string.Empty;
comboRO.Text = string.Empty;
comboLocation.Text = string.Empty;
comboSerial.Items.Clear();
comboPart.Items.Clear();
comboRO.Items.Clear();
comboLocation.Items.Clear();
}
else
{
dataGridFB.Rows.Clear();
}
ItemsLoad();
connection.Close(); // CLOSE HERE OR YOU CANNOT ENTER RECORDS SIMULTANEOUSLY
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
The OleDbCommand.ExecuteNonQuery returns the number of rows affected by the command. If there is no row to delete the return value will be zero. So it is easy to discover this situation
int rowsDeleted = command.ExecuteNonQuery();
if(rowsDeleted == 0)
MessageBox.Show("No Serial number found to delete");
else
....
Said that, remember that string concatenation to build command text is considered bad practice and you should never use it. A parameterized query is the only correct way to create commands that requires inputs from the user.....
string deleteEntry = "delete from Inventory where SerialNumber=#num"
command.CommandText = deleteEntry;
command.Parameters.Add("#num", OleDbType.VarWChar).Value = txtSerial.Text;
int deletedRows = command.ExecuteNonQuery();
The OleDbCommand.ExecuteNonQuery method you're using returns an Int32 which represents the number of rows affected. You could use this to find out whether a row was deleted or not.
if (command.ExecuteNonQuery() > 0)
{
// Row was deleted
}
else
{
// Row was not deleted
}
You can do a Console.WriteLine("Nothing to delete") in an if based statement, but if it is compiled and you can not see the console, try a MessageBox.Show("Nothing to delete") function after an if based statement.
if (command.ExecuteNonQuery == 0)
{
Console.WriteLine("0-removed")
}
else
{
Console.WriteLine("not deleted")
As an example...
private void timer1_Tick(object sender, EventArgs e)
if (command.ExecuteNonQuery == 0)
{
Console.WriteLine("0-removed")
}
else
{
Console.WriteLine("not deleted")

inserting multiple checkedlistbox values in one single row database using c#

I'm making a windows form where in all the checkedlist values are stored in one row. However it only stores one value.
Question is, is it possible to store all the checkedlist values in a single row in which only their assigned ids are stored?
This is my previous code below. if you find any mistakes or if you have any idea on how to edit to make it work, it would be a big help for me. Thanks!
foreach (DataRowView item in this.checkedListBox1.CheckedItems)
{
NpgsqlCommand cmd = new NpgsqlCommand("Insert into name(eid, name, famid) Values (#eid, #name, #famid)", conn);
cmd.Parameters.AddWithValue("#eid", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
string value = item.Row[0].ToString().Split(',');
cmd.Parameters.AddWithValue("#famcon", value);
cmd.ExecuteNonQuery();
}
Since you are using C#, use this code but gotta change the default name to yours.
private void button1_Click(object sender, EventArgs e)
{
try
{
string Str = "";
if (checkedListBox1.CheckedItems.Count > 0)
{
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
if (Str == "")
{
Str = checkedListBox1.CheckedItems[i].ToString();
label1.Text = Str;
}
else
{
Str += ", " + checkedListBox1.CheckedItems[i].ToString();
label1.Text = Str;
}
}
// Make your connection to the DataBase and insertion code starting within that area.
MessageBox.Show("Your selection is for :" + Str);
}
else
{
MessageBox.Show("Please select one name at least to work it out!");
}
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0],false);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}

Retrieve data for List box

I have inserted data from list box. I want to retrieve data for specific skill set in gridview.
for example if i select android in dropdownlist and press button it must give people who have android skill set only.
Does any body know how to do this
private string GetConnectionString()
{
//Where DBConnection is the connetion string that was set up in the web config file
return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO Table1 (Employees) VALUES";
sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
sc.Add(item.Text);
}
}
InsertRecords(sc);
}
Yes you can do this using where clause like this
string query="select * from Employees where skill= '" +yourvalue+ "'";
have your gridview datasource configured, during configuration whereever you have your SkillsetID or whateever that is, FOR THAT, use the "WHERE" clause which say that SkillSetID is bound to the "control" with ID lstBasePackageAsset with "selected value" or just "selected" i.e
gridview1.skillsetID = lstBasePackageAsset.selectedvalue ;
You will be done.
And please next time, or even now, let people know if it is VisualStudio query or any other developement source query. It is more easier in VS but require more programming code in command line (if you are doing that)
string query="select * from Employees where skill= '" +yourvalue+ "'";

Delete record from MDF database

I want to create simple application in C#. It should be windowsForms app, with service-based database added to project. In this I want to make table (ID, name, second name) and in program show name into listBox. Current name selected in listBox will be deleted (row will be deleted)
Can anyone help me how to do it? I have try with dataset, this is working, but after I close app and run it again, table is full with data again.
For saving records into database and loading them in a listbox you can see..
save-data-to-database-then-load-data-to-listbox
Now,for deleting a record from a listbox you can code like this..
protected void removeButton_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItem.Text == null)
{
MessageBox.Show("Please select an item for deletion.");
}
else
{
for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
{
if (ListBox1.Items[i].Selected)
{
DeleteRecord(ListBox1.Items[i].Value.ToString());
}
}
string remove = ListBox1.SelectedItem.Text;
ListBox1.Items.Remove(remove);
}
}
For deleting that record also from database use like this..
private void DeleteRecord(string ID)
{
SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING");
string sqlStatement = "DELETE FROM Table1 WHERE Id = #Id";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Id", ID);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Deletion Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}

Categories