How to use SQL Command Builder and SQL Data Apdater - c#

I read SQL Command Builder class from
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.aspx and I found that I can show update done on dataset/database using select and update command.
SQL Command Builder concept is clear if I am using single dataset but what if I want to use two different dataset?
Scenario: I am reading values from database into one dataset ds1; which is assign to sql adapter and sql command builder. Now, I am reading only selected values from ds1 and storing into second dataset ds2; which is not assign to sql data adapter and sql command builder.
I am concern if I am updating any data on ds2 whether it will update database or not. Also, how should I do it using SQL Command builder and SQL Adapter.
//primary dataset
ds = new ProductDataSet();
command = new SqlCommand(
"SELECT no, name, price, cost, dept FROM PRODUCTS", connection);
adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(ds, "table");
Primary dataset is fill on form load event. User will enter item no of his choice which will be search from primary ds and saved/display onto 2nd ds (2nd ds is not connected with with any adapter or command builder right now). For eg; 2nd ds have 3 items.
Now say user update any information on 2nd ds it should automatically update database and display on grid.
//2nd ds2 update code
for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
{
string item = ds2.Tables[0].Rows[i][0].ToString();
command = new SqlCommand("UPDATE PRODUCTS SET " + _colName + " = '" + _newValue + "'" + "WHERE ITEM_NO = '" + item + "'", Class1.conn);
datagrid.DataSource = ds2.Tables[0];
}
According to your suggestion if I am adding/declaring adapter/builder in above code it doesn't work. I am getting Table Mapping error.

Use another SQLAdapter and SQLCommandBuilder. The example on that page shows how to update your database. You just need to supply the fields to be updated in the form of a query, such as:
SELECT Name, Address, Phone, Email FROM Contact
and the command builder will generate the proper SQL UPDATE statement.

SqlCommandBuilder automatically generates INSERT, UPDATE and DELETE sql statements based on the SELECT statement for a single table.
For the Transact-SQL statements to be generated using SqlCommandBuilder, there are 2 steps
Step 1. Set the "SelectCommand" property of the SqlDataAdapter object
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand("SELECT_Query", con);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Students");
Step 2. Create an instance of SqlCommandBuilder class and associate the
SqlDataAdapter object created above using DataAdapter property of the SqlCommandBuilder object
SqlCommandBuilder builder = new SqlCommandBuilder();
builder.DataAdapter = dataAdapter;
Step 3. Updating records of ds1
dataAdapter.Update(ds1, "Students");

Related

How to update a DataGridView in a Windows form when the end-user adds selection criteria

I have a data grid view that shows all rows of a particular database table on a Windows form. Above the grid, I have text fields with corresponding buttons that a user can use to narrow down the data grid view by various criteria, such as By Customer Number, By Order Number, etc... I haven't been able to figure out how to accomplish this.
I've tried many examples I've found online, the most recent resulting the code below.
OleDbConnection connection = SerialsDatabaseDB.GetConnection();
string selectStatement
= "Select * "
+ "FROM Orders "
+ "WHERE CustomerNumber = #CustomerNumber";
OleDbCommand selectCommand =
new OleDbCommand(selectStatement, connection);
selectCommand.Parameters.AddWithValue("#CustomerNumber", custNumber);
OleDbDataAdapter dataAdapter =
new OleDbDataAdapter(selectStatement, connection);
DataSet dataSet = new DataSet("OrdersByCustomer");
connection.Open();
dataAdapter.Fill(dataSet, "OrdersByCustomer");
connection.Close();
dataGridView1.DataSource = dataSet;
dataGridView1.DataMember = "OrdersByCustomer";
Currently, I'm getting a "No value given for one or more required parameters" on the dataAdapter.Fill(dataSet, "OrdersByCustomer"); line.
Try your code with this change
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand);
Ole​DbData​Adapter has 4 constructors. One of them takes an instance of OleDbCommand. In your code you are creating it but you are not passing it into relevant constructor. The parameter you created and added to the selectCommand is just remaining unused. The exception you are getting is the result of this.

Updating data in multiple tables from datagrid

I'm trying to display data from multiple tables to a data grid and let the user edit the data and have it saved in my sql server.
I get an error message: Dynamic SQL generation is not supported against multiple base tables.
I declared my variables like so:
private NpgsqlDataAdapter da;
private DataSet ds;
private NpgsqlCommandBuilder cmdBuilder;
At load I've got this code:
string SELECT = "SELECT Table_1.Col_1, Table_1.Col_2, Table_2.Col_1, Table_2.Col_2 FROM Table_1 INNER JOIN Table_2 ON Table_1.ID = Table_2.ID";
conn.Open();
da = new NpgsqlDataAdapter(SELECT, conn);
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
And my save buton looks like this:
cmdBuilder = new NpgsqlCommandBuilder(da);
da.Update(ds);
I believe it's because SqlCommandBuilder is not suppose to work with multiple tables. Is there any other way of doing this?
I only need the data updated on Table_1 (user won't edit any data from Table_2) but I need data from both tables displayed on the datagrid.

Get DataGrid data from SQLite view

I'm working on an WPF application. It has a couple of TextBox fields and an DataGrid.
To create the SQLite database (with only one table) I have have done this...
SQLiteCommand command = new SQLiteCommand(connection);
command.CommandText = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name VARCHAR(100)...
And so on...
Now The query to create view is:
command.CommandText = "CREATE VIEW IF NOT EXISTS users_details AS SELECT name,adress...
And so on again.
This works flawless, but... I'm stuck on one problem. I want to connect that view "user_details" with my DataGrid.
Any guidance or part of solution would be appreciated...
You will need to create another SQLiteCommand to retrieve the data from the view and then use it as an ItemsSource for the DataGrid
SQLiteCommand command = new SQLiteCommand(connection);
command.CommandText = "SELECT * FROM users_details"
SQLiteDataAdapter da = new SQLiteDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
this.dataGrid.ItemsSource = dt.AsDataView();

How to update MySql table row through C# console application?

I am writing a console application and fetch data from MySql table .
Code :
string connection = "Server=localhoht;Database=data;Uid=root;Pwd=root123";
MySqlConnection dbcon = new MySqlConnection(connection);
MySqlCommand selectData;
dbcon.Open();
selectData = dbcon.CreateCommand();
selectData.CommandText = "SELECT user_id, user_name,user_type FROM win_user WHERE user_type=1 ORDER BY user_id ASC ";
MySqlDataReader juh = selectData.ExecuteReader();
And its working fine. Now I want to update a row with the code below :
string updatedata = "UPDATE win_user SET user_type='1' WHERE user_id= '1'";
MySqlDataAdapter MyData = new MySqlDataAdapter();
MyData.UpdateCommand = new MySqlCommand(updatedata, dbcon);
But its not working.
You can run the commend "UPDATE win_user SET user_type='1' WHERE user_id= '1'" in any sql client tools, eg, navicat, to verify wheather it's correct on your mysql database.
The MySqlDataAdapter could be used to update rows in a database table using the Update method.
The Update method (link is for SqlServer but the concept is the same) has many overload, but basically it requires a DataTable with rows modified in some way ([RowState != DataRowState.Unchanged][2]) so the MySqlDataAdapter can pick the rows changed and apply the DeleteCommand, UpdateCommand and InsertCommand defined in the adapter
Your code above doesn't shown any kind of interaction with a datatable and you have a call to the Update method so there is no way for the update to occur.
You could, of course execute directly your command without any adapter involved
EDITed to change every user_type not 1 to 1
string updatedata = "UPDATE win_user SET user_type=1 WHERE user_type <> 1";
MySqlCommand cmd = new MySqlCommand(updatedata, dbcon);
int numOfRowsChanged = cmd.ExecuteNonQuery();

Define table names for results of multiple SQL selects in a single query

For example if I run the following query:
select * from table1
select * from table2
And run it with a DB adapter (C#) I get a dataset with two tables.
How can I define the names for the result tables in SQL?
I can only do this inside the SQL. I don't have access to the c# code.
#Timothy Khouri: It can be done! EDIT: but not at the SQL level!
You can use TableMappings on the DataAdapter.
If the SelectCommand of a DataAdapter returns multiple result sets, the DataAdapter uses table mappings to fill corresponding DataTables in a DataSet. By default, the first result set will be filled to a DataTable named "Table", and the second result set will be filled to a DataTable named "Table1" etc.
SqlDataAdapter sqlDa = new SqlDataAdapter();
SqlCommand selectCmd = new SqlCommand();
selectCmd.CommandText = "spReturnMultpileResultSets";
selectCmd.CommandType = CommandType.StoredProcedure;
selectCmd.Connection = this.sqlConnection1;
sqlDa.SelectCommand = selectCmd;
// Add table mappings to the SqlDataAdapter
sqlDa.TableMappings.Add("Table", "Customers");
sqlDa.TableMappings.Add("Table1", "Orders");
// DataSet1 is a strongly typed DataSet
DataSet1 ds = new DataSet1();
this.sqlConnection1.Open();
sqlDa.Fill(ds);
this.sqlConnection1.Close();
Refs:
http://blogs.msdn.com/vsdata/archive/2007/03/08/tableadapter-multiple-result-sets.aspx
http://www.eggheadcafe.com/software/aspnet/32696845/strongly-typed-datasets.aspx

Categories