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
Related
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
I want to insert new record into the DataTable with DataAdapter.
There are 2 columns in Person table. FirstName and LastName.
I have a code like below.
SqlConnection connection;
DataSet dsPerson;
SqlDataAdapter adapter;
string connectionString = Properties.Resources.ConnectionString;
connection = new SqlConnection(connectionString);
dsPerson = new DataSet("PersonDataSet");
adapter = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Person", connection);
adapter.SelectCommand = selectCommand;
adapter.Fill(dsPerson, "Person");
string insertQuery = "INSERT INTO Person(FirstName, LastName) VALUES (#FirstName, #LastName)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add(new SqlParameter("#FirstName", SqlDbType.NVarChar));
insertCommand.Parameters["#FirstName"].SourceVersion = DataRowVersion.Current;
insertCommand.Parameters["#FirstName"].SourceColumn = "FirstName";
insertCommand.Parameters.Add(new SqlParameter("#LastName", SqlDbType.NVarChar));
insertCommand.Parameters["#LastName"].SourceVersion = DataRowVersion.Current;
insertCommand.Parameters["#LastName"].SourceColumn = "LastName";
adapter.InsertCommand = insertCommand;
But when I try to insert new Record into DataSet it appears in the DataSet. But it does not do insert new record into DataBase.
The Code for Insert is below.
connection.Open();
DataRow newRow = dsPerson.Tables["Person"].NewRow();
newRow["FirstName"] = "Joseph";
newRow["LastName"] = "Sword";
dsPerson.Tables["Person"].Rows.Add(newRow);
dsPerson.Tables["Person"].AcceptChanges();
dsPerson.AcceptChanges();
adapter.Update(dsPerson, "Person");
connection.Close();
I even try to trace queries sent to sql server With Express Profiler. And i saw that it does not send insert command to the database.
So what is the problem? How to solve it?
Thank you.
You should not call AcceptChanges methods of dataset and DataTable because DataAdapter.Update method affects only changed/added/deleted rows from datatable.
But after calling AcceptChanges all your DataRows will have Unchanged state.
See MSDN for reference about DataAdapter:
When an application calls the Update method, the DataAdapter examines
the RowState property, and executes the required INSERT, UPDATE, or
DELETE statements iteratively for each row, based on the order of the
indexes configured in the DataSet.
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();
I used SqlAdapter.Update() method to update the rows in a table.
For that I created Datatable and add values to that datatable.
DataTable dtTable = new DataTable("Product");
SqlConnection myLocalConnection = new SqlConnection(_ConnectionString);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from " + dtTable.TableName, myLocalConnection);
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.Update(dtTable);
When I using this command it insert new rows in the database rather than updating the existing rows. Why does this happen?
I think what is happening here is (As per your given code) your dataadapter is unable to recognize rows in your datatable it is nowhere related to your datatable here, So as a guess try to fill your datatable via dataadapter then modify your datatable and update it.
DataTable dtTable = new DataTable();
SqlConnection myLocalConnection = new SqlConnection(_ConnectionString);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("Select * from " +
dtTable.TableName, myLocalConnection);
SqlCommandBuilder builder= new SqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.Fill(dtTable,"Products" )
// Code to modify your datatable
mySqlDataAdapter.UpdateCommand = builder.GetUpdateCommand();
mySqlDataAdapter.Update(dtTable);
-- Hope it helps .
This is just an idea and not the solution...
// update command to update database table.
string strUpdateCommand =
"Update Students set Name = #Name, Gender = #Gender, Total = #Total where ID = #ID";
// create an instance of SqlCommand using the update command created above.
SqlCommand updateCommand = new SqlCommand(strUpdateCommand, con);
// specify the paramaters of the update command.
updateCommand.Parameters.Add("#Name", SqlDbType.NVarChar, 50, "Name");
updateCommand.Parameters.Add("#Gender", SqlDbType.NVarChar, 20, "Gender");
updateCommand.Parameters.Add("#Total", SqlDbType.Int, 0, "Total");
updateCommand.Parameters.Add("#ID", SqlDbType.Int, 0, "ID");
// associate update command with SqlDataAdapter instance.
dataAdapter.UpdateCommand = updateCommand;
I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.
SqlConnection DBConnection = new SqlConnection(ConnectionString);
//Opens the connection
DBConnection.Open();
//Creates a string to hold the query
string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";
//Creates an SQLCommand object to hold the data returned by the query
SqlCommand queryCommand = new SqlCommand(query, DBConnection);
//Uses the aforementioned SQLCommand to create an SQLDataReader object
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Creates a DataTable to hold the data
DataTable dataTable = new DataTable();
//This part actually loads the data from the query into the table
dataTable.Load(queryCommandReader);
dgvOutput.DataSource = dataTable;
The other example:
using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
{
DataTable Table = new DataTable();
newDA.Fill(Table);
dgvOutput.DataSource = Table;
}
You might try this or something similar:
SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text;
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;