How to Use an Update Statement in SQLDataAdapter - c#

I am trying to run an update statement after i built my sqldataadapter. I have column called INIT_PHASE in my table and if the INIT_PHASE is null or there is no data then i would like to set it to 1. I have tried but i can't seem to get it right the update statement. Pls. help. here is my code:
string ID = ddlPractice.SelectedValue;
string TYPE = DDL_TYPE.SelectedValue;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(#"select SET_SK, UNIT_NM, TYPE, INIT_PHASE FROM myTable WHERE UNIT_NM =#ID AND TYPE = #TYPE", con);
DataTable dtSETS = new DataTable();
da.SelectCommand.Parameters.AddWithValue("#ID", (ID));
da.SelectCommand.Parameters.AddWithValue("#TYPE", (TYPE));
da.Fill(dtSETS);
if (dtSETS.Rows.Count > 0)
{
DataRow dtSETS_row = dtSETS.Rows[0];
long SET_SK = dtSETS_row.Field<long>("SET_SK");
if (dtSETS_row.Field<string>("INIT_PHASE") == null)
{
//run update command here
update myTable set INIT_PHASE = 1;
}
}

One approach here would be to use the SqlCommandBuilder to build the UPDATE statement:
string ID = ddlPractice.SelectedValue;
string TYPE = DDL_TYPE.SelectedValue;
SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(
#"select SET_SK, UNIT_NM, TYPE, INIT_PHASE FROM myTable WHERE UNIT_NM =#ID AND TYPE = #TYPE",
con);
DataTable dtSETS = new DataTable();
da.SelectCommand.Parameters.AddWithValue("#ID", (ID));
da.SelectCommand.Parameters.AddWithValue("#TYPE", (TYPE));
da.Fill(dtSETS);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.UpdateCommand = builder.GetUpdateCommand();
if (dtSETS.Rows.Count > 0)
{
DataRow dtSETS_row = dtSETS.Rows[0];
long SET_SK = dtSETS_row.Field<long>("SET_SK");
if (dtSETS_row.Field<string>("INIT_PHASE") == null)
{
dtSETS_row["INIT_PHASE"] = 1;
}
}
da.Update(dtSETS);
Take note to the following lines of code. Here we are building the update command:
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.UpdateCommand = builder.GetUpdateCommand();
here we are literally modifying the DataRow so that it's RowState is changed to Modified:
dtSETS_row["INIT_PHASE"] = 1;
and then finally, here we are sending updates to the database with the Update method on the SqlDataAdapter:
da.Update(dtSETS);
What this is going to do is only send updates for the rows with a RowState of Modified.
NOTE: each of the ADO.NET objects should be wrapped in a using. Refactor your code to match this type of template:
using (SqlConnection con = new SqlConnection(...))
{
using (SqlDataAdapter da = new SqlDataAdapter(...))
{
}
}

If I understand correctly, you could execute directly a command to update just this field
if (dtSETS_row.Field<string>("INIT_PHASE") == null)
{
SqlCommand cmd = new SqlCommand(#"UPDATE myTable set INIT_PHASE = 1 " +
"WHERE UNIT_NM =#ID AND TYPE = #TYPE", con);
cmd.Parameters.AddWithValue("#ID", (ID));
cmd.Parameters.AddWithValue("#TYPE", (TYPE));
cmd.ExecuteNonQuery();
}
You need to open the connection though both for the SqlDataAdapter and for the following command

You will have to use SqlCommandBuilder class for updating data in disconnected mode. ie) DataSet and Data Adapters.

Related

SqlDataAdapter handle error - object is not created

I have this error:
Invalid object name 'sap.AfdelingsrapportACTUAL'.
Which is because this table is not created yet.
I need to implement a check in my SqlDataAdapter - so if is null or doesnt get anything it moves on. But i really doesnt know how to.
I think it should be around my SqlDataAdapter but i could be wrong
Code
DataTable sqldt = new DataTable();
string sqlQuery = #"Select * from " + table;
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, sqlcon);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(sqldt);
}
What i think it should look like:
public static bool CompareDataTables(DataTable dt, string table, string connectionString)
{
DataTable sqldt = new DataTable();
string sqlQuery = #"Select * from " + table;
SqlConnection sqlcon = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, sqlcon);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
if (da == "doesnt have any table")
{
return true;
}
else
{
da.Fill(sqldt);
}
}
int sqlCols = sqldt.Columns.Count;
int excelCols = dt.Columns.Count;
if (excelCols == sqlCols)
{
return false;
}
else return true;
}
One way would be first check for the existence of the data table.
follow the sample given here:
Check if table exists in SQL Server

C# & SQL Server : searching all database columns and populating datagrid

I am writing a a C# application, and I am stuck at searching the database and populating a data grid view. However I want to use this with command builder.
The issue is, I need the search to work across all columns in the database. I thought using OR and LIKE statements would do this. But instead I get either invalid syntax or no column name exists in the search.
Does anyone know a solution?
My current .cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
NOTE:
I am aware of using parameters, I am simply using this to see if it will work when I will add parameters later.
this is what I use to get everything back into a DataTable
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(List<SqlParameter> sqlParameters, string connStr, string storedProcName)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcName;
sqlCmd.CommandTimeout = 5000;
foreach (var sqlParam in sqlParameters)
{
sqlCmd.Parameters.Add(sqlParam);
}
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
sqlParameters.Clear();
return dt;
}
//'places the call to the system and returns the data as a datatable
public DataTable GetDataAsDatatable(string connStr, string query)
{
var dt = new DataTable();
var sqlCmd = new SqlCommand();
using (var sqlconn = new SqlConnection(connStr))
{
sqlCmd.Connection = sqlconn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = query;
sqlCmd.CommandTimeout = 5000;
using (var sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
}
}
return dt;
}
hopefully this is pretty self explanatory to you, however pass in a list of SQL Parameters, connection string, and the stored procedure name, or use the second one where you pass in the inline SQL and the connection string.
I think you are missing ' in the query. Try this...
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE '" +txtSearchJob.Text+ "' OR [Manufacturer] LIKE '" +txtSearchJob.Text+ "')";

Issue while deleting row using DataSet

Following code does not delete a row from dataset and dont update the database....
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select *from RegisterInfoB", con);
ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"] == "praveen")
{
dr.Delete();
}
}
ds.Tables[0].AcceptChanges();
How to resolve this problem...How do I update my sql server database...by deleting a row from dataset..
I hope this will work for you:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"].ToString().Trim() == "praveen")
{
dr.Delete();
}
}
adpt.Update(ds);
Two Changes
1st: if (dr["FirstName"].ToString().Trim() == "praveen") trimming the blank spaces in your db's FirstName Field.
2nd : use adpt.Update(ds); to update your DB.
Another Way to doing it:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
string firstName= "praveen"; // this data will get from calling method
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
string deleteQuery = string.Format("Delete from RegisterInfoB where FirstName = '{0}'", firstName);
SqlCommand cmd = new SqlCommand(deleteQuery, con);
adpt.DeleteCommand = cmd;
con.Open();
adpt.DeleteCommand.ExecuteNonQuery();
con.Close();
Similary, you can write query for UpdateCommand and InsertCommand to perform Update and Insert Respectively.
Find rows based on specific column value and delete:
DataRow[] foundRows;
foundRows = ds.Tables["RegisterTable"].Select("FirstName = 'praveen'");
foundRows.Delete();
EDIT: Adding a DeleteCommand to the data adapter (based on example from MSDN)
Note: Need an Id field here instead of FirstName, but I don't know your table structure for RegisterInfoB. Otherwise, we delete everyone named "praveen".
// Create the DeleteCommand.
command = new SqlCommand("DELETE FROM RegisterInfoB WHERE FirstName = #FirstName", con);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#FirstName", SqlDbType.NChar, 25, "FirstName");
parameter.SourceVersion = DataRowVersion.Original;
// Assign the DeleteCommand to the adapter
adpt.DeleteCommand = command;
To update a database with a dataset using a data adapter:
try
{
adpt.Update(ds.Tables["RegisterTable"]);
}
catch (Exception e)
{
// Error during Update, add code to locate error, reconcile
// and try to update again.
}
Sources: https://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.120).aspx
https://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.120).aspx
hope that resolve the problem,
Try it:
var connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
var selectQuery = "Select * from RegisterInfoB";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataSet dataSet = new DataSet();
// you can use the builder to generate the DeleteCommand
adapter.DeleteCommand = builder.GetDeleteCommand();
// or
// adapter.DeleteCommand = new SqlCommand("DELETE FROM RegisterInfoB WHERE Id= #Id", connection);
adapter.Fill(dataSet, "RegisterInfoB");
// you can use the foreach loop
foreach (DataRow current in dataSet.Tables["RegisterInfoB"].Rows)
{
if (current["FirstName"].ToString().ToLower() == "praveen")
{
current.Delete();
}
}
// or the linq expression
// dataSet.Tables["RegisterInfoB"]
// .AsEnumerable()
// .Where(dr => dr["FirstName"].ToString().ToLower().Trim() == "praveen")
// .ToList()
// .ForEach((dr)=> dr.Delete());
var result = adapter.Update(dataSet.Tables["RegisterInfoB"]);
also you can add some events and put a breakpoint to see if the state is changing or if there is an error that prevent changes on the source:
dataSet.Tables["RegisterInfoB"].RowDeleted += (s, e) =>
{
var r = e.Row.RowState;
};
dataSet.Tables["RegisterInfoB"].RowDeleting += (s, e) =>
{
var r = e.Row.RowState;
};

Read data from a database in C#

I have created a table name glossary in a database named ChatBotDataBase in SQL Server. I want to read the data in a special column of the table.
To do so, I have written this code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = #"Data Source=shirin;Initial Catalog=ChatBotDataBase;
Integrated Security=True";
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = sc;
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
But there is an error in last line.
The error is :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll.
And here is a print screen of the mentioned table:
Can anyone help please?
Looks like you are confusing the Datatable called table with your database table in your sql server. In your image you show us the glossary table in your sql server, not the DataTable called table.
You get this error because you create an empty DataTable called table with DataTable table = new DataTable() but you didn't even fill your table. That's why it doesn't have any rows by default.
SqlCommand cmd = new SqlCommand("SELECT * FROM glossary");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(table);
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter.
using(SqlConnection sc = new SqlConnection(conString))
using(SqlCommand cmd = sc.CreateCommand())
{
cmd.CommandText = "SELECT * FROM glossary";
...
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
sda.Fill(table);
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
}
Below code will help you
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
sda.Fill(table , "glossary");
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
You haven't executed the query or populated the table. It is empty. It has no columns and no rows. Hence the error.
Frankly, though, I strongly suggest using a typed class model, not any kind of DataTable. With tools like "dapper", this can be as simple as:
var list = conn.Query<Glossary>("SELECT * FROM glossary").ToList();
With
public class Glossary {
public int Id {get;set}
public string String1 {get;set} // horrible name!
....
public int NumberOfUse {get;set}
}
Dear kindly first fill your table with the data.
And you should use checks because if there is no data then you get a proper message.check is below..
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
else if(dt.Rows.Count > 0)
MessageBox.Show("Table is empty");
And other advice is that you should display data into DataGrid.... Displaying data from Database into a message box is not a good programming approach..
For displaying DataTable into DataGrid in C# is as simple as below.
SqlCommand cmd = new SqlCommand("select * from student",con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
dt.TableName = "students";
da.Fill(dt);
dataGridView1.DataSource =dt;
using System.Data.Odbc;
OdbcConnection con = new OdbcConnection("<connectionstring>");
OdbcCommand com = new OdbcCommand("select * from TableX",con);
OdbcDataAdapter da = new OdbcDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds,"New");
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables["New"];
you can get the connection string from:
http://www.connectionstrings.com/

update table in database from datatable

I load data from database table like this...
using (view_adapter = new SqlDataAdapter("select * from TVServiceProvider", connection_string))
{
using (dt = new DataTable())
{
view_adapter.Fill(dt);
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName.Substring(0, 2).Equals("id"))
dt.Columns[i].ReadOnly = false;
}
bs.DataSource = dt;
}
}
Where SqlDataAdapter view_adapter and DataTable dt. To apply changes to database I've created method
void View_Adapter_Click(object sender, EventArgs e)
{
try
{
view_adapter.Update(dt);
dt.AcceptChanges();
}
catch (Exception exc)
{
this.radLabelElement1.Text = exc.Message;
}
}
But when I click the button I've got an exception. It requires update command. Where and what command I should use?
You must create UpdateCommand and DeleteCommand for you view_adapter.
EDIT:
The code must look like this:
SqlDataAdapter view_adapter = new SqlDataAdapter();
view_adapter .SelectCommand = new SqlCommand(queryString, connection);
view_adapter .UpdateCommand = new SqlCommand(updateCommadString, connection);
view_adapter .DeleteCommand = new SqlCommand(deleteCommadString, connection);
using (SqlConnection connection = new SqlConnection(connectionString))
{
view_adapter.Fill(dt);
return dt;
}
Well, something is wrong or not clear in your code.
The view_adapter variable is initialized within a using block statement.
Thus, when exiting from the using block, the view_adatpter will be disposed by the framework and unusable in the click event. (like you have never called new to initialize it).
I suspect that you have another problem here. Using statement
A part from this, to automatically create the UpdateCommand, InsertCommand and DeleteCommand required to perform CRUD operations with a DataAdapter you could use a SqlCommandBuilder.
(This is possible only if you use one table in the select statement and that table has a primary key defined)
So to summarize everything:
string queryString = "select * from TVServiceProvider";
view_adapter = new SqlDataAdapter(queryString, connection_string);
SqlCommandBuilder builder = new SqlCommandBuilder(view_adapter)
builder.GetUpdateCommand(); // Force the building of commands
view_adapter.Fill(dt);
then your click event should works as is now.
This code is not related to yours, but may help you, If you give it a look. I got it from MSDN
public static SqlDataAdapter CreateCustomerAdapter(
SqlConnection connection)
{
SqlDataAdapter adapter = new SqlDataAdapter();
// Create the SelectCommand.
SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
"WHERE Country = #Country AND City = #City", connection);
// Add the parameters for the SelectCommand.
command.Parameters.Add("#Country", SqlDbType.NVarChar, 15);
command.Parameters.Add("#City", SqlDbType.NVarChar, 15);
adapter.SelectCommand = command;
// Create the InsertCommand.
command = new SqlCommand(
"INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (#CustomerID, #CompanyName)", connection);
// Add the parameters for the InsertCommand.
command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
adapter.InsertCommand = command;
// Create the UpdateCommand.
command = new SqlCommand(
"UPDATE Customers SET CustomerID = #CustomerID, CompanyName = #CompanyName " +
"WHERE CustomerID = #oldCustomerID", connection);
// Add the parameters for the UpdateCommand.
command.Parameters.Add("#CustomerID", SqlDbType.NChar, 5, "CustomerID");
command.Parameters.Add("#CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
SqlParameter parameter = command.Parameters.Add(
"#oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.UpdateCommand = command;
// Create the DeleteCommand.
command = new SqlCommand(
"DELETE FROM Customers WHERE CustomerID = #CustomerID", connection);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add(
"#CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand = command;
return adapter;
}
What actually worked for me from Steve and Hamlet's suggestions is the following. I had one hiccup because I tried to do an accept changes on my rows and table before doing the view adapter update. The accept changes in only needed to save the changes to the datatable before reusing the datatable for displaying in a gridview or other operations.
SqlDataAdapter viewAdapter = new SqlDataAdapter("Select * From Users", DBConn);
SqlCommandBuilder builder = new SqlCommandBuilder(viewAdapter);
viewAdapter.UpdateCommand = builder.GetUpdateCommand();
DataTable Users = new DataTable();
viewAdapter.Fill(Users);
foreach (DataRow user in Users.Rows)
{
foreach (DataColumn c in Users.Columns)
{
Console.WriteLine(c.ColumnName);
if (c.DataType != typeof(DateTime))
{
// Clean up empty space around field entries
user[c.ColumnName] = user[c.ColumnName].ToString().Trim();
}
}
// user.AcceptChanges();
// Do not do an accept changes for either the table or the row before your ViewAdapter Update.
// It will appear as though you do not have changes to push.
}
// Users.AcceptChanges();
viewAdapter.Update(Users);

Categories

Resources