How can I add data from DataTable to database table directly? - c#

How can I add data from a DataTable to a database table directly?
I have searched on the internet not being able to get information from any site.
I have a DataTable and now I want to add that data to a database table.
importData.Tables[1];
for(int r = 0; r< totalrecoreds; r++;)
{
Array test[] = importData.Tables[1].Rows[r].ItemArray.ToArray;
}
What can I do? Do I have to add data one by one using for loop or is there any other method?

Provided that the schema of the DataTable is the same as the schema of the database table you can just use a DataAdapter to insert the data.
using(var connection = new SqlConnection(...))
using(var adapter = new SqlDataAdapter("SELECT * FROM TABLENAME", connection))
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.InsertCommand = builder.GetInsertCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
adapter.Update(importData.Tables[1]);
}
If the schemas differ you have to add mappings to the DataAdapter, like the MSDN DataAdapter example illustrates.

Related

Limiting the number of retrieved rows using Fill in ADOMD

The following C# code runs a DAX statement and retrieves a DataTable. This works fine, but now I need to retrieve from the database up to N rows. Is there a way to limit the number of rows returned by the Fill function? If not, how can I retrieve the top N rows? Note that I need to keep this generic for any DAX statement, so you shouldn't change the DAX itself. Also, I don't want to retrieve all the data and then take the first N rows as the data may be too large.
public static DataTable runDaxStatement(int maxRows) {
var con = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
AdomdConnection conn = new AdomdConnection(con);
DataSet ds = new DataSet();
ds.EnforceConstraints = false;
AdomdCommand cmd = new AdomdCommand("evaluate customers", conn);
AdomdDataAdapter da = new AdomdDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
}
Came across the following TOPN function in the documentation.
This can be used to return the top N rows of the specified table.
For example
public static DataTable runDaxStatement(int maxRows) {
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
using(AdomdConnection connection = new AdomdConnection(connectionString)) {
string commandText = $"EVALUATE TOPN({maxRows}, customers, <orderBy_expression_here>)";
AdomdCommand command = connection.CreateCommand();
command.CommandText = commandText;
DataSet dataSet = new DataSet(){
EnforceConstraints = false
}
AdomdDataAdapter adapter = new AdomdDataAdapter(command);
adapter.Fill(dataSet);
return dataSet.Tables[0];
}
}

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");

About fetching data from datatable to gridviewin c#

I am trying to get column names for particular data table.
I tried with this code.
datagridFieldCreation.AutoGenerateColumns = false;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select * from Add_Information ", con);
sda.Fill(dt);
datagridFieldCreation.DataSource = dt;
I am getting full data that is there in table. But I want only column names to be displayed one by one. Can any one help me out??
You can use ExecuteReader(CommandBehavior.SchemaOnly)):
DataTable schema = null;
using (var con = new SqlConnection(connection))
{
using (var schemaCommand = new SqlCommand("SELECT * FROM Add_Information", con))
{
con.Open();
using (var reader = schemaCommand.ExecuteReader(CommandBehavior.SchemaOnly))
{
schema = reader.GetSchemaTable();
}
}
}
datagridFieldCreation.DataSource = schema;
SchemaOnly:
The query returns column information only. When using SchemaOnly, the
.NET Framework Data Provider for SQL Server precedes the statement
being executed with SET FMTONLY ON.
The column name is in the first column of every row.
foreach (DataRow col in schema.Rows)
{
Console.WriteLine("ColumnName={0}", col.Field<String>("ColumnName"));
}
Adpated from: Using GetSchemaTable() to retrieve only column names
You can use:
SELECT * FROM YOURTABLENAME WHERE 0=1
Yes for sure, it is simple query which has a conditional statement which is always returning false, so each time you execute the query no rows will be extracted and only columns you will get so you can easily put up these columns in you DataGridView.

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();

Using SqlDataAdapter to insert a row

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.

Categories