Using SqlDataAdapter to insert a row - c#

I want to insert a row into the Database using SqlDataAdapter. I've 2 tables (Custormers & Orders) in CustomerOrders database and has more than thousand records. I want to create a GUI (TextBoxes) for adding new customer & orders into the Database to their respective tables.
How should I do it?
I guess the method that is usually followed is
dataAdapter = new SqlDataAdapter (sqlQuery, conn);
dataSet = new DataSet();
da.Fill(dataSet);
Now take the values from textboxes (or use DataBinding) to add a new row into the dataSet and call
da.Update(dataSet);
But the Question is Why should I fetch all other records into dataSet using da.Fill(dataSet ) in the first place? I just want to add a single new record.
For this purpose what I'm doing is, Creating the schema of the Database in the DataSet. like this:
DataSet customerOrders = new DataSet("CustomerOrders");
DataTable customers = customerOrders.Tables.Add("Customers");
DataTable orders = customerOrders.Tables.Add("Orders");
customers.Columns.Add("CustomerID", Type.GetType("System.Int32"));
customers.Columns.Add("FirstName", Type.GetType("System.String"));
customers.Columns.Add("LastName", Type.GetType("System.String"));
customers.Columns.Add("Phone", Type.GetType("System.String"));
customers.Columns.Add("Email", Type.GetType("System.String"));
orders.Columns.Add("CustomerID", Type.GetType("System.Int32"));
orders.Columns.Add("OrderID", Type.GetType("System.Int32"));
orders.Columns.Add("OrderAmount", Type.GetType("System.Double"));
orders.Columns.Add("OrderDate", Type.GetType("System.DateTime"));
customerOrders.Relations.Add("Cust_Order_Rel", customerOrders.Tables["Customers"].Columns["CustomerID"], customerOrders.Tables["Orders"].Columns["CustomerID"]);
I used DataBinding to bind these columns to respective text boxes.
Now I'm confused! What should I do next? How to use Insert command? Because I didn't give any dataAdapter.SelectCommand so dataAdapter.Update() wont work I guess. Please suggest a correct approach.

Set the select command with a "0 = 1" filter and use an SqlCommandBuilder so that the insert command is automatically generated for you.
var sqlQuery = "select * from Customers where 0 = 1";
dataAdapter = new SqlDataAdapter(sqlQuery, conn);
dataSet = new DataSet();
dataAdapter.Fill(dataSet);
var newRow = dataSet.Tables["Customers"].NewRow();
newRow["CustomerID"] = 55;
dataSet.Tables["Customers"].Rows.Add(newRow);
new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataSet);

You can fill the dataSet with an empty set e.g.:
da = new SqlDataAdapter ("SELECT * FROM Customers WHERE id = -1", conn);
dataSet = new DataSet();
da.Fill(dataSet);
Then you add your rows and call update.
For this scenario though it would probably be better not to use SqlDataAdapter. Instead use the SqlCommand object directly for insertion. (Even better, use LINQ to SQL or any other ORM)

SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True");
SqlDataAdapter da=new SqlDataAdapter("Insert Into Employee values("+textBox1.Text+",'"+textBox2.Text+"','"+textBox3.Text+"',"+textBox4.Text+")",con);
DataSet ds = new DataSet();
da.Fill(ds);
I have to do first time. You can try it . It works well.

Related

mysql selecting with join to dataset and datatable in c#

I searched a lot but could not find the right solution.
Lets say ill select data like:
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[...]; //<== here is the problem
}
and I want to add this to a datatable,
How do I call the table in this case ?
Is it tableA ?
Does it matters how I name it ? (could I name it foobar as well???)
It is unclear what you are really asking for, but due to the length of comment and clarification, putting into an answer.
If you are trying to get multiple query results back from MySQL into a single "DataSet" (which can contain multiple tables), your query could contain multiple sql-statements and each would be returned into the dataset for you as different table results. For example, if you did something like...
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText =
#"select * from TableA;
select * from TableB;
SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
Your dataset would have 3 tables in it in direct correlation of the queries provided..
ds.Tables[0] = result of tableA all records.
ds.Tables[1] = result of tableB all records.
ds.Tables[2] = result of JOIN query tableA and tableB.
you could then refer to them locally however you need to...
ds.Tables[0].TableName = "anyLocalTableNameReference".
var t1Recs = ds.Tables[0].Rows.Count;
etc... or even create your own individual datatable variable name without having to explicitly reference the dataset and table array reference
DataTable myLocalTableA = ds.Tables[0];
DataTable myLocalTableB = ds.Tables[1];
DataTable myJoinResult = ds.Tables[2];
Hopefully this clarifies a bunch with the querying and referencing of multiple data results returned and how to then reference to the tables individually.

Populate Devexpress GridView using a DataAdapter and SqlCommand in code

I have a little problem with populating my DevExpress Gridview, I want to have a two level gridview and using SqlCommand. At first I created a Dataset and added two tables and also defined relation for them. But it does not work. Can you help me find my problem?
Here is my code
string owner = "SELECT [OBJECTID],[Name] ,[Family] ,[Father] ,[Dftarche] ,[Birthday] ,[education] ,[home_address] ,[farm_address] ,[ensurance] ,[phone] ,[home_number] ,[owner_id] FROM [dbo].[OWNER]";
string property = "SELECT [number] ,[owner_ID] ,[GPSId] ,[Energy],[corp_type] ,[Pool],[irrigation] ,[variety] ,[trees] ,[utilizat] ,[address] ,[water_hour] ,[w_source] ,[w_inche],[w_dore],[NoeMalekiat],[MotevasetBardasht],[Area] ,[OBJECTID],[Shape] FROM [dbo].[Property] ";
string strConnString = Properties.Settings.Default.land_gisConnectionString;
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand command = new SqlCommand(owner, con);
SqlDataAdapter adapter = new SqlDataAdapter();
System.Data.DataSet dsMain = new System.Data.DataSet();
adapter.SelectCommand = command;
adapter.Fill(dsMain, "First Table");
adapter.SelectCommand.CommandText = property;
adapter.Fill(dsMain, "Second Table");
dsMain.Tables.Add(iFeatureSet.DataTable.Copy());
adapter.Dispose();
command.Dispose();
DataRelation newRelation = new DataRelation("املاک شخصی", dsMain.Tables["First Table"].Columns["owner_id"], dsMain.Tables["Second Table"].Columns["owner_ID"]);
dsMain.Relations.Add(newRelation);
GridAttrebuteTable.DataSource = dsMain.Tables[2];
// gridView5.DataSource = dsMain.Tables[1];
dataGridView1.DataSource = dsMain;
I searched and found this http://msdn.microsoft.com/en-us/library/bh8kx08z.aspx and it seems my code is right but it does not show anything in grids
Thank you very much for your help
I Could figure out how to fix it.It works fine now(Above Code is edited) but now If I add a new DataTable I do not know why it does not work again
You need a new GridView for each detail table. You can't display both a master and detail in the same GridView.
Try this example

How do I use adapter.Update(table)

string qry="select *from mom";
Dataset dataset= new Dataset();
SqlDataAdapteradap adap= new SqlDataAdapter(qry,con);
adap.Fill(dataset,"MOM");
DataRow drow = dataset.Tables["MOM"].NewRow();
drow[0] = MRefDDL.SelectedItem.Text;
drow[1] = project.Text.Trim();
drow[2] = agendatopic3.Text.Trim();
drow[3] = presenter3.Text.Trim();
drow[4] = discus.Text.Trim();
drow[5] = conclu.Text.Trim();
drow[6] = "1";
dataset.Tables["MOM"].Rows.Add(drow);
adap = new SqlDataAdapter();
adap.Update(dataset, "MOM");
Here I have One Dataset with MOM Table which fill by data adapter
when after add new row into data set. iwant add this row into database
table with help of adapter.update() Method.But its giving me error:-
Update requires a valid InsertCommand when passed DataRow collection
with new rows.
In the dataadapter, there are insert, update and delete queries that you need to add. The wizard can also do that for you. You can also:
adp.InsertCommand = New SqlCommand(sql, connection)
etc.
Look at https://stackoverflow.com/a/21239695/1662973 for more detailed info.
you are reinitializing the dataadapter just before the Update() method. Please comment this.
//adap = new SqlDataAdapter(); // make this line comment
adap.Update(dataset, "MOM");

How to combine two DataSet Tables into one

I am attempting to do as stated above combing two DataSet.tables into one table. I was wondering if it were possible to do so. I call my stored procedure and it returns my values I set them to a table. (All illustrated below).
Tried:
Adding both table names in the Mapping section ("Tables", IncomingProductTotals).
Adding both as one table in Mapping Section ("Tables", IncomingProductTotals1) ("Tables", TotalDownTimeResults1)
Doing lots of research most I can find is on sql joining tables.
SqlCommand cmd = new SqlCommand("L_GetTimeTotals", conn);
cmd.Parameters.Add("#startTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker2.SelectedDate;
cmd.Parameters.Add("#endTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker3.SelectedDate;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
var ds = new DataSet();
ds.Tables.Add("IncomingProductTotals");
ds.Tables.Add("IncomingProductTotalsA");
ds.Tables.Add("IncomingProductTotalsB");
ds.Tables.Add("IncomingProductTotals1");
ds.Tables.Add("IncomingProductTotalsA1");
ds.Tables.Add("IncomingProductTotalsB1");
da.TableMappings.Add("Table", "IncomingProductTotals");
da.TableMappings.Add("Table1", "IncomingProductTotalsA");
da.TableMappings.Add("Table2", "IncomingProductTotalsB");
da.TableMappings.Add("Table3", "IncomingProductTotals1");
da.TableMappings.Add("Table4", "IncomingProductTotalsA1");
da.TableMappings.Add("Table5", "IncomingProductTotalsB1");
da.Fill(ds);
ds.Tables.Remove("IncomingProductTotalsA");
ds.Tables.Remove("IncomingProductTotalsB");
ds.Tables.Remove("IncomingProductTotalsA1");
ds.Tables.Remove("IncomingProductTotalsB1");
ExcelHelper.ToExcel(ds, "TimeTotals.xls", Page.Response);
Have you tried the Merge method? http://msdn.microsoft.com/en-us/library/system.data.datatable.merge(v=vs.110).aspx
foreach(var t in ds.Tables.Skip(1))
{
t.Merge(ds.Tables[0]);
}
edit:
Skip is Linq. You can use this too:
for(int i = 1; i < ds.Tables.Count - 1; i++)
ds.Tables[i].Merge(ds.Tables[0]);

Updating strongly typed Dataset from local Sql Compact database

I created with Visual Studio 2010 Express a Sql Compact Database (sdf-File), with several tables and relations. From this database I generated a strongly typed dataset.
Now I want to fill the dataset with the content from the database.
So I used following code to connect to the database and fill the dataset.
//My strongly typed dataset
localData = new LokalStorageDataSet();
//SqlCe-Connection
localConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\TempStorage.sdf; Password='xyc';Persist Security Info=True");
localConnection.Open();
SqlCeCommand command = new SqlCeCommand("SELECT * FROM progstates", localConnection);
localDataAdapter = new SqlCeDataAdapter(command);
localDataAdapter.Fill(localData);
The problem is that no rows were added to my dataset, although in the database there are rows.
If I use a SqlCeReader to read the results of the SqlCeCommand, the reader return the rows:
SqlCeDataReader dr = command.ExecuteReader();
while (dr.Read())
{
...
}
Can you give me the reason why my dataset don't get the rows from the table in the dataset?
EDIT: I saw that in my dataset a new datatable were created named 'Table' with the same columns like the one I requested (progstate) but also this datatable has a rowCount of 0.
EDITED *****
Try This :-
//My strongly typed dataset
localData = new LokalStorageDataSet();
//SqlCe-Connection
localConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\TempStorage.sdf; Password='xyc';Persist Security Info=True");
SqlCeCommand command = new SqlCeCommand("SELECT * FROM progstates", localConnection);
localConnection.Open();
var dataReader = command.ExecuteReader();
localData.Load(dataReader,LoadOption.Upsert,localData.Tables[0]);
localConnection.Close();
Or You cant do this with DataAdapter like this :-
localDataAdapter = new SqlCeDataAdapter();
SqlCeCommand command = new SqlCeCommand("SELECT * FROM progstates", localConnection);
localDataAdapter.SelectCommand = command;
localConnection.Open();
localDataAdapter.SelectCommand.ExecuteNonQuery();
localDataAdapter.Fill(localData.Tables[0]);
localConnection.Close();

Categories