update database using SqlDataAdapter in C# - c#

I have below code to update my database table when button is clicked but it doesn't work.
protected void Button_Click(object sender, EventArgs e)
{
HasinReservation.Entities.Db.Transaction dt = new Transaction();
SqlConnection connection = new SqlConnection(
#"Data Source=192.x.x.x\Sql2008;Initial Catalog=GardeshgariKish;User ID=cms;Password=xxxxx;MultipleActiveResultSets=True;Application Name=EntityFramework");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(
"Update Transaction SET IsCancelled = 1 WHERE BarCodeNumber = #Value1", connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
string barcode = dgvData.Rows[0].Cells[12].Text;
sqlCmd.Parameters.AddWithValue("Value1", barcode);
connection.Close();
}

I am troubled by your implementation of Entity Framework but then not using the framework for what it was designed...
You have configured your data adapter and the command, and even opened the connection... but you have not actually executed the command.
sqlCmd.ExecuteNonQuery();
I understand that your actual business logic may have been replaced with this simple CRUD operation, but the main reason that we use the Entity Framework is to avoid writing any T-SQL in our business logic. Why didn't you use the framework to commit the change:
protected void Button3_Click(object sender, EventArgs e)
{
// cancel the selected transaction
string selectedBarcode = dgvData.Rows[0].Cells[12].Text;
using(var dataContext = new HasinReservation.Entities.Db())
{
var transaction = dataContext.Transaction.Single(t => t.Barcode == selectedBarcode);
transaction.IsCancelled = true;
dataContext.SaveChanges();
}
}
This in itself may not be a great solution but it uses the framework to do exactly what you attempted to do manually.

Why are you trying to use a SqlDataAdapter to execute an UPDATE statement? When constructing a SqlDataAdapter with a SqlCommand object, that command object represents the SELECT command for the adapter. An UPDATE statement doesn't select anything, and a SELECT command doesn't update anything.
Get rid of the SqlDataAdapter entirely and just execute the command:
sqlCmd.ExecuteNonQuery();
You'll probably also want to add some error handling so exceptions don't reach the UI (and to ensure the connection is properly closed on error conditions). You also don't seem to be doing anything with that Transaction object, so you can probably get rid of that too.

Related

c# update database isn't working

So I've searched the net to find a solution and what I found is that when we execute F5 in visual studio, it actually copies the original database into a new one and it uses the copy in the code so the changes you'd have made wouldn't be there and they told me to set the database properties to "Copy if newer" and it isn't working, I don't get any error messages but the original is not being updated.
I made a test to see if this code was updating at least the copy and it is...
After running my application when I see the database the changes aren't there
So I want to update the original database how do I do that?
private void button3_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["NembManagement.Properties.Settings.NembDatabaseConnectionString"].ConnectionString;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("UPDATE Alunos SET Nome = #a WHERE Id=1", connection))
{
DataTable AlunosInfo = new DataTable();
connection.Open();
command.Prepare();
command.Parameters.Clear();
command.Parameters.AddWithValue("#a","aff");
command.ExecuteNonQuery();
//test to see if it was updating the copy and it is
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Alunos WHERE Alunos.Id=1 ", connection);
adapter.Fill(AlunosInfo);
}
}
I found the solution somehow, i changed my database property Copy to nevercopy and i got another error saying that connection could not be opened so i solved this one by correcting the connection string in the app config

Adding records to MS Access database through C#

I am attempting to add items to an Access database in C#. I have code that seems to work (I can open and close a database), but the button click event produces errors. I have been searching on Google for the whole afternoon but no joy. My code is:
private void button26_Click(object sender, EventArgs e)
{ //Setup tab LoadDatabase
try
{
connection.Open();
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO Main('Prop', 'Value', 'Default','Type') VALUES('one', 'Kelly', 'Jill','one')";
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
connection.Close();
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
connection.Close();
}
}
And the error I get is:
Error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method)
? at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CrewCheifSettingsBeta3.Form1.button26_Click(Object sender, EventArgs e) in C:\Somepath\Form1.cs:line 49
Clearly something wrong with the connection string, and that it's not SQL-injection proof either.
The problem is well known. A command need to know the connection to use to execute the command text. However you have other problems in your code.
Connection objects (like commands) should not be global, but created when they are needed and destroyed after. The using statement is very usefull here because you don't have to explicitly close and destroy these objects and you will never have resource leaks when an exception occurs.
Second, when you use field names that are also reserved keywords in your database you should enclose these name in some kind of escape characters. These characters for Access are the open/close brackets not the single quote.
private void button26_Click(object sender, EventArgs e)
{
try
{
string cmdText = #"INSERT INTO Main
([Prop], [Value], [Default],[Type])
VALUES('one', 'Kelly', 'Jill','one')";
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
connection.Open();
cmd.ExecuteNonQuery();
button26.Text = "Done Insert";
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
}
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
}
}
Finally I don't know if your fields are of text type. You pass literal texts so they should be of text type and remember to use parameters when you switch this simple code to your actual values.
Assign Connection property as below line.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
Per #Steve's comment, there is no connection associated with the command when you just instantiate it like that. You need to either set the Connection property of the command or better yet use connection.CreateCommand() to create the command in the first place in which case it will already be associated with the connection (cleaner).

unable to insert data in sql database with c# even no error accur

hy I want to insert new record in my database but am unable to do this even code is fully error free, I added following code in my button click event
here is my code
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query="insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
I mean insert query is not updating my database, even when I execute my query it return 2 not 0 which means query applied successfully,
not really an answer but the steps you need to take to see whats going on, so we can help you are a bit longer...
you will need to execute the following query, once in your sql management studio, and once in your program ... i suspect the result being different in both cases
select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()
on the code side please use this:
private void btn_Update_Click(object sender, EventArgs e)
{
// string query="insert into users(Name,Password)values('ubaid','ali')";
// cmd = new SqlCommand(query, con);
// con.Open();
// cmd.ExecuteNonQuery();
// MessageBox.Show("Record Updated Successfully");
// con.Close();
string query="select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()";
cmd = new SqlCommand(query, con);
con.Open();
using(var rdr = cmd.ExecuteReader())
{
rdr.read();
MessageBox.Show($"{rdr.GetString(0)}, {rdr.GetString(1)}, {rdr.GetString(2)}, {rdr.GetString(3)} ");
}
con.Close();
}
the result should show the name of the server, its instance name, the name of your DB and of the default schema you are using in both cases
example result for my testmachine would look like this:
srv9, MSSQLSERVER, testdb, dbo
expectation in your case:
you will get 2 different results which means that your sql management studio, where you are trying to check if your code did the right thing, is using a different server, instance, database or schema
with the provided information it will be possible to change the used connectionstring so both your clients work on the same database...

Populating my drop down list C# asp.net

I am trying to get a drop down list to display data from MYSQL database, database table name is Pet and I am trying to get the information from Specie.
Now the code looks good to me but it is not running so its always best to get another pair of eyes to look over it.
Thanks,
All help is appreciated.
connection string
MySqlConnection cs = new MySqlConnection(#"Data Source = 000.000.00.000;username=benoatsc_admin;password=****; Initial Catalog = dbname; Integrated Security = true");
drop down code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlCommand cd = new MySqlCommand("SELECT * FROM Pet", cs);
cs.Open();
MySqlDataReader ddl = cd.ExecuteReader();
DdPetList.DataSource = ddl;
DdPetList.DataValueField = "Specie";
DdPetList.DataTextField = "Specie";
DdPetList.DataBind();
cs.Close();
cs.Dispose();
}
There are a few problems here:
You should likely move this code to the Page_Load method. I would assume that you want this DropDownList populated when the page loads for the user. Otherwise, the DropDownList is never populated with the data from your MySQL Database, hence you will not be able to trigger the SelectedIndexChanged event when there is no index to possibly change.
MySQL Connector/Net makes use of unmanaged resources. These should be disposed of when they are finished being used. The .NET Framework offers an elegant way to ensure that objects utilizing unmanaged resources are disposed of in the form of using statements. It is best practice to use them.
When MySqlConnection, MySqlDataReader, etc. should not only be disposed of when they are done being used, but they should also be closed. Thankfully, when dispose() is called on these objects their close() methods are called as well.
So piecing this all together yields this piece of code:
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new MySqlConnection(/* Your connection string here */))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT * FROM Pet", conn))
{
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
DropDownList1.DataSource = reader;
DropDownList1.DataValueField = "Specie";
DropDownList1.DataTextField = "Specie";
DropDownList1.DataBind();
}
}
}
}
}
I hope this all helps. If you need any clarifications, I will gladly provide it.
This would be a comment but i don't have the reputation,
what error message are you receiving ?
your connection string has got both trusted connection set to true and you are providing credentials,
remove one of them.

using winforms to insert data in sql database , drawback of opening connection frequently

I am developing a front-end sales application.
Is this an efficient way of inserting data multiple times into a sql table, from a single button:
private void button1_Click(object sender, EventArgs e)
{
c.Open();
string w = "insert into checkmultiuser(username) values (#username)";
SqlCommand cmd = new SqlCommand(w, c);
cmd.Parameters.Add("#username", SqlDbType.VarChar);
cmd.Parameters["#username"].Value = textBox1.Text;
//cmd.ExecuteNonQuery();
cmd.ExecuteReader();
c.Close();
}
What are its drawbacks? One would be that again and again the connection is opened and closed when the button is clicked which would effect the speed greatly.
You ar edoing the right way: see this question: to close connection to database after i use or not? too.
Perhaps don't do the database insert for each entry, but store each entry in a DataSet, then insert them all at once, a la a save button.
For each entry do this:
String s = textBox1.Text;
If ( *\Enter validation logic*\ )
{
//Insert data into DataSet
}
else
{
//Throw error for user.
}
Then once you're ready to commit to DB, insert each item from the DataSet, similar to the examples in the other answers here.
I would open the connection once when the form opens and re-use that connection until the form is closed.
As for inserting records, the code you have is right.
From a resource management point of view it would be better if you can work out how many times you need to insert the data and then perform the operation in the one button click, perhaps iterating through a loop until the correct amount of insert operations has been completed. This means you are not constantly opening and closing the connection with each button press but instead opening it, performing the insert queries and closing the connection.
Also I recommend that you implement your code with the "using" statement, this way it will automatically handle the disposal and release of resources.
private void button1_Click(object sender, EventArgs e, string[] value)
{
try
{
using(SQLConnection c = new SQLConnection(connectionString))
using(SQLCommand cmd = new SQLCommand(c))
{
c.Open();
string w = "insert into checkmultiuser(username) values (#username)";
cmd.CommandText = w;
cmd.Parameters.Add("#username", SqlDbType.VarChar);
for(int i = 0; i < value.Length; i++)
{
cmd.Parameters["#username"].Value = value[i];
cmd.ExecuteReader();
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
If you can create the SQLConnection in the method then it will also allow you create it in a using statement, again taking care of managing and releasing resources.
In terms of the statement you are using I can't see any problems with it, you're using parameterized queries which is a good step to take when interacting with SQL databases.
References:
try-catch - MSDN
I don't think you should have to worry about the time lag due to opening and closing a connection, particularly if it is happening on a manually triggered button click event. Human perceivable response time is about 200 milliseconds. At best, I'd guess someone could click that button once every 100 milliseconds or so. Plenty of time to open and close a connection.
If, however, you are dealing with a routine that will be connecting to your database, you could pass in the connection, include a using statement as Mr. Keeling mentioned already, and just verify that it is ready.
Here is yet another approach, which returns a DataTable (since your original post displayed executing a Data Reader):
public static DataTable UpdateRoutine(SQLConnection c, string value) {
const string w = "insert into checkmultiuser(username) values (#username)";
DataTable table = new DataTable();
using(SQLCommand cmd = new SQLCommand(w, c)) {
cmd.Parameters.Add("#username", SqlDbType.VarChar);
cmd.Parameters["#username"].Value = value;
try {
if ((cmd.Connection.State & ConnectionState.Open) != ConnectionState.Open) {
cmd.Connection.Open();
}
using (SqlDataReader r = cmd.ExecuteReader()) {
table.Load(r);
}
}
return table;
} catch(SqlException err) { // I try to avoid catching a general exception.
MessageBox.Show(err.Message, "SQL Error");
}
return null;
}

Categories

Resources