UPDATE command not updating data - c#

I have two oledbcommnds used for updating a table in a database.One of them is working (adding data to empty fields) but the other one designed to empty the data, does not work.Any ideas?
First Update commnd that is working (adds values to empty data):
conn.Open();
OleDbDataAdapter adapter1 = new OleDbDataAdapter();
adapter3.UpdateCommand = conn.CreateCommand();
adapter3.UpdateCommand.CommandText = "UPDATE table SET Occup=Yes, Profesor=?";
adapter3.UpdateCommand.Parameters.AddWithValue("p1", "name");
adapter3.UpdateCommand.ExecuteNonQuery();
conn.Close();
The second one, that does not work (replaces values)
conn.Open();
OleDbDataAdapter adapter3 = new OleDbDataAdapter();
adapter3.UpdateCommand = conn.CreateCommand();
adapter3.UpdateCommand.CommandText = "UPDATE table SET Occup=No, Profesor=?";
adapter3.UpdateCommand.Parameters.AddWithValue("p1", "replace_prof_name");
adapter3.UpdateCommand.ExecuteNonQuery();
conn.Close();
When running the second code, I don't get any errors. I have put a counter and it shows the correct number of operations but I see no modfifications.

You are wrongly referring adapter3 instead of adapter1..
Try this
conn.Open();
OleDbDataAdapter adapter1 = new OleDbDataAdapter();
adapter1.UpdateCommand = conn.CreateCommand();
adapter1.UpdateCommand.CommandText = "UPDATE table SET Occup=Yes, Profesor=?";
adapter1.UpdateCommand.Parameters.AddWithValue("p1", "name");
adapter1.UpdateCommand.ExecuteNonQuery();
conn.Close();
conn.Open();
OleDbDataAdapter adapter3 = new OleDbDataAdapter();
adapter3.UpdateCommand = conn.CreateCommand();
adapter3.UpdateCommand.CommandText = "UPDATE table SET Occup=No, Profesor=?";
adapter3.UpdateCommand.Parameters.AddWithValue("p1", "replace_prof_name");
adapter3.UpdateCommand.ExecuteNonQuery();
conn.Close();

Related

Storing multiple values from an SQL select statement

I have an SQL select query that will return multiple values, but I cannot find a way to store/access them. I am using Visual Studio 2015 and an Access database.
Below is my most recent attempt using a data table/grid view.
string now = DateTime.Today.ToString("dd/MM/yyyy");
//Establish and open new database connection.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase32BITConnectionString"].ToString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmd.CommandText = String.Format ("select Rating from [RATINGS] where Today_Date like #now and Name like #name");
cmd.Parameters.AddWithValue("#now", now);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection = con;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
con.Close();
testGridView.DataSource = dt;
name is a variable passed into the method. I don't necessarily need it stored in a data table, i just need to be able to access the results individually to average them (array?).
Any advice would be much appreciated

Adding data to data row of database in c#

I am facing a little problem in my code to add data to sql database attached with my program in ASP.net/C#. Here's code:
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
SqlConnection cnn = new SqlConnection(ConnectionString);
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Id from TableName";
cmd.Connection = cnn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds, " TableName ");
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataRow drow = ds.Tables["TableName"].NewRow();
drow["Id"] = TextBox1.Text;
ds.Tables["TableName "].Rows.Add(drow);
da.Update(ds, " TableName ");
string script = #"<script language=""javascript"">
alert('Information have been Saved Successfully.......!!!!!.');
</script>;";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myJScript1", script);
Even when I entered any integer value to the text box, it shows an error message that object is not set to an instance on code:
DataRow drow = ds.Tables["TableName"].NewRow();
Please guide.
Thanks.
This seems like a very bad way of inserting data. Have you looked at the Entity Framework or Linq2Sql? Alternatively you could just use a standard SqlCommand and set the CommandText yourself.
Any of these would provide a cleaner solution.
Eg: With ADO.NET (Connecting to SQLite):
var conn = new SQLiteConnection(string.Format(Constants.SQLiteConnectionString, "db.db3"));
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction()) {
using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "INSERT INTO TableName (Id) VALUES (#Id)";
cmd.Parameters.AddWithValue("#Id", someTextVariable);
cmd.ExecuteNonQuery();
}
}

SQL DataTable Update?

I'm not sure, but I think I may have taken a wrong path here. I am trying to update my customer table on my SQL Server. I Connected with a SQLDatareader and then loaded that into my Datatable. I have made all the changes I wanted and now I can't figure out how to get the changes back up. I thought that the "myDataTable.AcceptChanges();" would trigger that to happen but it doesn't.
SqlConnection myConnection = new SqlConnection();
SqlCommand myCommand;
DataTable myDataTable;
SqlDataReader myReader;
myCommand = new SqlCommand();
myCommand.CommandText = " SELECT * FROM customer";
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
myDataTable = new DataTable();
myDataTable.Load(myReader);
// Make Data changes here
myDataTable.AcceptChanges();
MyDataTable.Dispose();
MyCommand.Dispose();
MyConnection.Dispose();
You can use a TableAdapter to commit your changes back to the database. Check out this link for details.
TableAdapter.Update()
In such case you need to use a DataAdapter which has an Update property that takes your Update Query Command.
Even you can use Command Builder and then get the UpdateCommand from CommandBuilder.
Sample Code from MSDN
SqlDataAdapter catDA = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories", nwindConn);
catDA.UpdateCommand = new SqlCommand("UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID" , nwindConn);
catDA.UpdateCommand.Parameters.Add("#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter workParm = catDA.UpdateCommand.Parameters.Add("#CategoryID", SqlDbType.Int);
workParm.SourceColumn = "CategoryID";
workParm.SourceVersion = DataRowVersion.Original;
DataSet catDS = new DataSet();
catDA.Fill(catDS, "Categories");
DataRow cRow = catDS.Tables["Categories"].Rows[0];
cRow["CategoryName"] = "New Category";
catDA.Update(catDS);
MSDN Link

Prepared SELECT statement in .Net

I can't understand what I am doing wrong, I can't seem to SELECT with a prepared statement. However I can INSERT with a prepared statement.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
cmd.fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
Any advice on this would be greatly appreciated!
To fill a DataSet you will need a DataAdapter.
Try this:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.SelectCommand = cmd;
dAdap.Fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
You need to use SqlDataAdapter
DataAdapter represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database.
The SqlDataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source
Check the following syntax:
private static DataSet SelectRows(DataSet dataset,
string connectionString,string queryString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, connection);
adapter.Fill(dataset);
return dataset;
}
}

Whats missing using OleDbDataAdapter.Update to update Access.mdb file?

With the following code below I have managed to open an Access.mpd database and read rows from the table Saved.
However when I try to change data or add new rows I works fine as long as the program is running but nothing seem to be saved to the access.mdb file.
Update: OleDbCommand apparently cannot simply be modified inside the DataAdapter.
Update: AcceptChanges was by me mistakenly used. If used it tells the affected rows to not be updated.
With these updates the code now works. Still I'm looking for understanding of the issue so explanations why will be appreciated. Also If the fixed code is the way to go.
string connection = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\...\Access.mdb;Persist Security Info=True";
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter da = new OleDbDataAdapter();
OleDbCommand cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.SelectCommand = cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.InsertCommand = cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.UpdateCommand = cmd;
cmd = new OleDbCommand();
cmd.CommandText = "Saved";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = conn;
da.DeleteCommand = cmd;
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.InsertCommand = cb.GetInsertCommand();
da.DeleteCommand = cb.GetDeleteCommand();
da.UpdateCommand = cb.GetUpdateCommand();
PbDataSet ds = new PbDataSet();
da.Fill(ds, "Saved");
PbDataSet.SavedDataTable table = ds.Tables["Saved"] as PbDataSet.SavedDataTable;
Here I try to change the data, which works. However it is not saved to file. this now works!
PbDataSet.SavedRow sr = table.Rows[0] as PbDataSet.SavedRow;
sr.berAktiv = true; //Changeing data here
sr.AcceptChanges();
da.Update(table as DataTable);
sr = table.NewSavedRow();
sr.rtAktiv = true;
table.AddSavedRow(sr);
table.AcceptChanges();
da.Update(table as DataTable);
No errors are given anywhere.
How can I fix this, so that the data is saved on the file?
How can I verify, in the running program, that it has really been saved, other than reopen the file?
What I can't see is that you're generating the update statements (or let generate them) anywhere...
//Select data
DataSet dataSet = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, db);
dataAdapter.FillSchema(dataSet, SchemaType.Source);
dataAdapter.Fill(dataSet);
//Make changes to the data in the data set...
//Write changes to the mdb
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(dataAdapter);
dataAdapter.Update(dataSet);

Categories

Resources