Hello trying to delete several rows of the table according to a condition, however i need some help with it, basically i want to delete all rows, while the condition is true and then stop and leave the rest untouched.
EDIT: Regarding the comments i apologize, im fairly new to programming, sorry if not doing things correctly im new to this website as well.
private void button1_Click(object sender, EventArgs e)
{
string varsql2check = "";
do{
SqlConnection conn = new SqlConnection(#"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd");
conn.Open();
string varsql = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' "; //sql query
SqlCommand cmd = new SqlCommand(varsql, conn);
SqlDataReader dr = cmd.ExecuteReader();
} while(varsql2check = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120);");
dr.Close();
conn.Close();
}
What you need to do is:
private void button1_Click(object sender, EventArgs e)
{
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' ";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120)";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
}
}
}
}
while (check);
}
Generally what I have done by editing your code is:
Add the using statement in order to release the resources from the established connections.
You should be using the returned types from the exeqution of the queries. The ExecuteNonQuery() will return the numbers of rows affected, in our case we are particularly interested in the rows returned from the select statement after the delete query. We create a reader and depending of the number of rows, in our case we are only interested if there are rows or no, branch accoringly. If we get no rows from the select (everything is deleted) we just continue, if we get nothing (reader.HasRows returns false) we repeat the delete query and check again.
Simple as that.
Related
I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.
is there something wrong with my codes. I already try another codes but the problem is still the same. I've been solving this error for a couple of weeks now, and i can't figure it out how to solve it. And also I already try some another code but the problem is still the same.
I want to save a multiple row from dataGrid to my database.
here's the codes that i use to save a multiple row
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conString = new MySqlConnection("datasource = localhost; port = 3306; Initial catalog = dbnewsystem; username = root;password = 1234");
MySqlCommand command1 = new MySqlCommand("INSERT INTO purchaseorder (orNo, ProdNo, Quantity, total)" +
"VALUES(#ORNo,#ProductNo,#quantity,#total )", conString);
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
conString.Open();
command1.ExecuteNonQuery();
command1.Connection = conString;
conString.Close();
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "pos_save";
if (command1.ExecuteNonQuery() == 1)
{
MessageBox.Show("saved");
}
else
{
MessageBox.Show("Sorry Nothing to be Update");
}
conString.Close();
}
change sequence
command1.Connection = conString;
command1.ExecuteNonQuery();
You have implemented wrong sequence:
...
conString.Open(); // Connection opened
command1.ExecuteNonQuery(); // Try executing (fail)
command1.Connection = conString; // Connection assigned
Change to
conString.Open(); // Connection opened
command1.Connection = conString; // Connection assigned
command1.ExecuteNonQuery(); // Try executing (fail)
A better design is
// Wrap IDisposable into using
using (MySqlConnection conString = new MySqlConnection("...")) {
conString.Open();
// Make SQL Readable
string sql =
#"INSERT INTO purchaseorder(
orNo,
ProdNo,
Quantity,
total)
VALUES(
#ORNo,
#ProductNo,
#quantity,
#total)";
// Wrap IDisposable into using
using (MySqlCommand command1 = new MySqlCommand(sql, conString)) {
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
command1.ExecuteNonQuery();
}
}
I'm having trouble extracting the SQL data I need from the below query. I've looked on MSDN and followed their examples, but for some reason the executereader is not reading the data and returning it to the textbox, after clicking the button. I have added a response to ensure the connection is open, and it is each time pressed. This is an extract of the code, the only thing I have omitted from here is the sqlconnection detail:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
//set up the SQL command
SqlCommand command = new SqlCommand("Use Waste_Test; select * from Bidston_HWRC where MCN_No = #MCN", conn);
//open the server connection
conn.Open();
//define parameter for SQL query
command.Parameters.Add("#MCN", SqlDbType.Int);
command.Parameters["#MCN"].Value = TextBox17.Text;
Response.Write("<script>alert('You are connected')</script>");
//Execute the query on the server
SqlDataReader rdr = command.ExecuteReader();
Response.Write("<script>alert('It's worked')</script>");
while (rdr.Read())
{
TextBox6.Text = rdr["Waste_Description"].ToString();
}
}
}
first of all, you need to use HasRowsin order to ensure that query return some result, if no record return then you can show a message in label. Since you are getting the MCN value from textbox, then you need to parse it into int. Try the following code.
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand("select * from Bidston_HWRC where MCN_No = #MCN", conn);
conn.Open();
Command.Parameters.AddWithValue("#MCN", Int32.Parse(TextBox17.Text));
//Execute the query on the server
SqlDataReader rdr = command.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
TextBox6.Text = rdr["Waste_Description"].ToString();
}
}
else
{
// show 'no records found'
}
rdr.Close();
conn.Close();
}
}
Im trying to add items in the comboBox (cmbInstructor) namely the last names (instructorLN) however, my code does not seem to work. Any ideas on where I went wrong?
private void cmbInstructor_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(mycon);
MySqlCommand cmd = new MySqlCommand("SELECT * FROM instructor WHERE instructorType ='" + labelClass.Text + "'", conn);
string instructorLN = "";
conn.Open();
MySqlDataReader myReader = null;
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
instructorLN = myReader["instructorLN"].ToString();
}
cmbInstructor.Items.Add(instructorLN);
}
As far as I can see, you are adding only last value that your SELECT returns.
Move your
cmbInstructor.Items.Add(instructorLN);
line into to the while statement as;
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
By the way, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connection and command and reader automatically.
using(var conn = new MySqlConnection(mycon))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM instructor WHERE instructorType = #type";
cmd.Parameters.Add("#type", labelClass.Text);
conn.Open();
using(var myReader = cmd.ExecuteReader())
{
while (myReader.Read())
{
cmbInstructor.Items.Add(myReader["instructorLN"].ToString());
}
}
}
Application — one TextBlock, one Button. + SQL database — one table.
I'm trying to read from sql to textblock, when i click the button, but it does not work.
private void nextButton_Click(object sender, RoutedEventArgs e)
{
GetSqlData();
}
private void GetSqlData()
{
string connectionString = #"Data Source=Jama-Dharma\sqlexpress;Initial Catalog=Cars;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(connectionString);
using (sqlConnection)
{
string sqlQuery = #"SELECT c.Name FROM CarsCatalog c";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
nameTextBlock.Text = sqlReader.GetString(0);
}
sqlConnection.Close();
}
}
How to make that when click on button, obtain the next ID values from SQL.
From a quick glance, it looks like your while loop just overwrites the textblock. Update the textblock text AFTER you exit the loop. Try something like
var sb = new StringBuilder();
while (sqlReader.Read())
{
sb.AppendLine(sqlReader.GetString(0));
}
nameTextBlock.Text = sb.ToString();
You can save last ID you got till now, and get next ID which is greater than this saved id.
e.g:
using (var sqlConnection = new SqlConnection(...))
{
string sqlQuery = #"SELECT c.Name,c.ID FROM CarsCatalog c where c.ID > "
+ lastID.ToString();
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCommand.ExecuteReader();
if (sqlReader.Read())
{
nameTextBlock.Text = sqlReader.GetString(0);
lastID = sqlReader.GetInt(1);
}
}