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.
Related
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;
Hello guys I have got this code:
SqlCommand scom = new SqlCommand(
"INSERT INTO klient(name,surname)
values(#kname,#ksurname)",
conn);
scom.Parameters.AddWithValue("#kname", kname.Text);
scom.Parameters.AddWithValue("#ksurname", ksurname.Text);
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM klient", spojeni);
SDA.Fill(dt);
conn.Close();
It should insert data from textboxes: kname, ksurname, but it closes the form without showing them in MS SQL table klient
Missing the ExecuteNonQuery call
SqlCommand prikaz = new SqlCommand("INSERT INTO klient(name,surname) values(#kname,#ksurname)", spojeni);
prikaz.Parameters.AddWithValue("#kname", kname.Text);
prikaz.Parameters.AddWithValue("#ksurname", ksurname.Text);
spojeni.Open();
prikaz.ExecuteNonQuery();
......
A command should be executed to update the database...
You haven't executed the command.
prikaz.ExecuteNonQuery();
The above stated problem is due to the missing executenonquery() statement, add this statement in your code
spojeni.Open();
prikaz.ExecuteNonQuery();
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
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;
So I have some code like this:
DataSet dataSet = new DataSet();
DataTable dataTable1 = new DataTable("Table1");
DataTable dataTable2 = new DataTable("Table2");
DataTable dataTable3 = new DataTable("Table3");
DataTable dataTable4 = new DataTable("Table4");
dataSet.Tables.Add(dataTable1);
dataSet.Tables.Add(dataTable2);
dataSet.Tables.Add(dataTable3);
dataSet.Tables.Add(dataTable4);
SqlDataAdapter dataAdapter1 = new SqlDataAdapter("SELECT * FROM Table1 WHERE ID = 1", sqlConnection);
SqlDataAdapter dataAdapter2 = new SqlDataAdapter("SELECT Column1, Column2, Column3 FROM Table2", sqlConnection);
SqlDataAdapter dataAdapter3 = new SqlDataAdapter("SELECT Column1, Column2, Column3 FROM Table3", sqlConnection);
SqlDataAdapter dataAdapter4 = new SqlDataAdapter("SELECT Column1, Column2, Column3 FROM Table4", sqlConnection);
SqlCommandBuilder commandBuilder1 = new SqlCommandBuilder(dataAdapter1);
SqlCommandBuilder commandBuilder2 = new SqlCommandBuilder(dataAdapter2);
SqlCommandBuilder commandBuilder3 = new SqlCommandBuilder(dataAdapter3);
SqlCommandBuilder commandBuilder4 = new SqlCommandBuilder(dataAdapter4);
dataAdapter1.Fill(dataTable1);
dataAdapter2.FillSchema(dataTable2, SchemaType.Source);
dataAdapter3.FillSchema(dataTable3, SchemaType.Source);
dataAdapter4.FillSchema(dataTable4, SchemaType.Source);
//do a bunch of code that updates the one row from Table1
//and adds lots of new rows to Table2, Table3, Table4
dataAdapter1.Update(dataTable1);
dataAdapter2.Update(dataTable2);
dataAdapter3.Update(dataTable3);
dataAdapter4.Update(dataTable4);
dataSet.AcceptChanges();
Is there anyway to make this a lot simpler? What would happen if the computer crashed on the line after "dataAdapter2.Update(dataTable2);"? I would like to be able to somehow use just one Update call to update everything. Is that possible?
Also, is this even the best way to do this? With "this" being creating a bunch of new rows in multiple tables depending on what is in one specific row in one specific table.
You can pass a dataset into a DataAdapter's Update statement, which will update all of the tables in the dataset. UPDATE: No, it doesn't. DataAdapters always update only one table. The overload to Update() that takes a DataSet as its parameter, from the MSDN documentation, "Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table"." Sorry for the confusion. The rest of the answer is still valid, though.
If you want to assure that all the updates succeed or fail as an atomic unit, use the SqlTransaction object:
DataSet ds = new DataSet();
// do something with the dataset
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlConnection cn = new SqlConnection(connString);
cn.Open();
SqlTransaction trans = cn.BeginTransaction();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
// set the InsertCommand, UpdateCommand, and DeleteCommand for the data adapter
dataAdapter.InsertCommand.Transaction = trans;
dataAdapter.UpdateCommand.Transaction = trans;
dataAdapter.DeleteCommand.Transaction = trans;
try
{
dataAdapter.Update( ds );
trans.Commit();
}
catch
{
trans.Rollback();
}
cn.Close();