Update a database field - c#

As part of an application that I am trying to develop is to update records according to the service type. Hence, the Status attribute is graded from 1 to 8 (In progress = 3 and Complete = 5). I made my code but it seems not working as I try to pass values and test update the current service type as the following:
IF progress then update to 4
IF Completed then update 6
class Program
{
static void Main(string[] args)
{
int Bend = 4;
int Complete = 6;
List<int> Status = new List<int>();
foreach (int i in Status)
{
if (i == 3)
{
SqlConnection con = new SqlConnection(#"Data Source=
(localdb)\Projects;Initial Catalog=FLS_DB;Integrated
Security=True;Connect Timeout=30;Encrypt=False;");
con.Open();
SqlCommand cmd = new SqlCommand("Update Calls set
Service =#Service", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Service", Bend);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
else if (i == 5)
{
SqlConnection con = new SqlConnection(#"Data Source=
(localdb)\Projects;Initial Catalog=FLS_DB;Integrated
Security=True;
Connect Timeout=30;Encrypt=False;");
con.Open();
SqlCommand cmd = new SqlCommand("Update Calls set
Service =#Service", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Service", Complete);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Any help would be much appreciated!

Your code is missing a WHERE statement to update only the records that match the conditions i == 3 or i == 5, thus it seems that you don't need a loop.
You just sets Service column to the new values Bend and Complete for all records that contain the value 3 or 5 in the Service column
using(SqlConnection con = new SqlConnection(....))
using(SqlCommand cmd = con.CreateCommand())
{
con.Open();
// Sets to 4 all records with 3
cmd.CommandText = "Update Calls set Service=#Service WHERE Service=3"
cmd.Parameters.AddWithValue("#Service", Bend);
int rowsUpdatedToBend = cmd.ExecuteNonQuery();
// No need to recreate the command, just change the commandtext and
// the value of the parameter #service
cmd.CommandText = "Update Calls set Service=#Service WHERE Service=5"
cmd.Parameters["#Service"].Value = Complete
rowsUpdatedToComplete = cmd.ExecuteNonQuery();
MessageBox.Show("You have changed " + rowsUpdatedToBend + " rows to Bend state\r\n" +
"You have changed " + rowsUpdatedToComplete + " rows to Complete state");
}

Does your connection string correct?
You are opening the connection twice by if condition
Put a break point and check where the programm is going
Assuming the first point is correct; could you try something like this (code edited):
string commandText = "UPDATE Calls SET Service=Service + 1 WHERE Service = 3 OR Service = 5;";
string connectionString = #"Data Source=
(localdb)\Projects;Initial Catalog=FLS_DB;Integrated
Security=True;Connect Timeout=30;Encrypt=False;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
try
{
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Related

C# Sqlite no update

Dashboard1 class this code checks for all rated work and adds up the sum total of rate and is used in the update query to update the user who did the work
{
// rate
if (listView1.SelectedItems.Count > 0)
{
if (comboBox1.Text == "")
{
MessageBox.Show("Warning : Select Rate value");
}
else
{
Author au = new Author();
au.rateReview(Convert.ToInt32(comboBox1.Text), Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text));
List<int> score = new List<int>();
string sql = "select work.rate from work WHERE work.id ="+ listView1.SelectedItems[0].SubItems[0].Text+";";
SQLiteConnection conn = new SQLiteConnection("data source =DatabaseFile.db3");
SQLiteCommand cmd = new SQLiteCommand(conn);
conn.Open();
cmd.CommandText = sql;
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
score.Add(Convert.ToInt32(reader["rate"].ToString()));
}
conn.Close();
res = score.AsQueryable().Sum();
// MessageBox.Show(res.ToString());
au_update_assigned();
string sql1 = "Update user Set score = "+res+" where id =" + userid + ";";
Database db = new Database();
db.insert(sql1);
MessageBox.Show(sql1);
}
}
else
{
MessageBox.Show("Error : Select Work from List");
}
}
Database class
Insert function is called from the database class
public void insert(string query)
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand(conn);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
} ```
The button even is from a **dashboard1 class** when the insert function is from the **database class** I am using sqlite I have checked for syntax error exception error but I just won't seem to up to update. It first queries for all user rated work then creates a sum total which is supposed to be part of the update command all fields have been filled
you need a connection opened and a commad to execute SQL instruction, try change:
Database db = new Database();
db.insert(sql1);
MessageBox.Show(sql1);
to:
conn.Open();
SQLiteCommand cmd2 = new SQLiteCommand(conn);
cmd2.CommandText="Update user Set score = "+res+" where id =" + userid + ";";
cmd2.ExecuteNonQuery ( );
conn.Close();
or pass connection to insert function:
public void insert(string query, SQLiteConnection _conn )
{
_conn.Open();
SQLiteCommand cmd = new SQLiteCommand(_conn);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
_conn.Close();
}
and call:
db.insert(sql1, cnn);

Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows

I created the following code:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = #headword WHERE Id = #id", conn);
command.Parameters.AddWithValue("#headword", headword);
command.Parameters.AddWithValue("#id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change.
If I run the code manually in the database the change takes place. But it won't work with C#.
Also the result variable are holding the right number of affected rows (1 in this case).
I'm not sure I have to flush the changes or something else.
Thanks for your help and best regards
Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=#headword" +
" WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
}

can't read int value from sql database

I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}

My Delete Query is not being working

I,m designing a CMS(campus Management System) and i wana delete some record...but its neither working nor generate any error...just return zero in "result " varaiable mentioned in code
public void DeleteAnnouncement(BusinessObject bo)
{
string ConnStr = Connection();
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
string query = "Delete from Anouncement where AnnouncementID=#i";
SqlCommand cmd = new SqlCommand(query, conn);
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine("\t============================================\n\n");
}
}
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
You're missing "#" in front of parameter name.
Correct: SqlParameter p1 = new SqlParameter("#i", bo.A_ID);
Your code works and deletes a record from Anouncement table, if AnnouncementID matches with the value of bo.A_ID, if value of bo.A_ID doesn't match with AnnouncementID, cmd.ExecuteNonQuery(); returns 0. If it's not deleting that means AnnouncementID doesn't match with the value of bo.A_ID.
But I suggest improve you code through using statement, this using statement ensures that Dispose is called even if an exception occurs while methods on the object are called.
string ConnStr = Connection();
string query = "Delete from Anouncement where AnnouncementID=#i";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
try
{
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine
("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine
("\t============================================\n\n");
}
}
catch (Exception ex)
{
//Do your exception handling work
}
}
}

How to run multiple SQL commands in a single SQL connection?

I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.

Categories