how to insert DataTable to a database table in Csharp
时间: 2024-05-09 15:16:59 浏览: 9
To insert a DataTable into a database table in C#, you can use a DataAdapter to update the table with the contents of the DataTable. Here's an example code snippet:
```
using System.Data;
using System.Data.SqlClient;
// First, create a DataTable with some data
DataTable dt = new DataTable();
// Add columns to the DataTable
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
// Add some rows to the DataTable
dt.Rows.Add(1, "Alice");
dt.Rows.Add(2, "Bob");
dt.Rows.Add(3, "Charlie");
// Next, create a connection to your database
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);
// Create a DataAdapter to save the data from the DataTable into the database
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = new SqlCommand("INSERT INTO myTable (ID, Name) VALUES (@ID, @Name)", connection);
adapter.InsertCommand.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
adapter.InsertCommand.Parameters.Add("@Name", SqlDbType.VarChar, 50, "Name");
// Fill the changes in the DataTable into the database using the DataAdapter
adapter.Update(dt);
```
Note that you will need to replace `myServerAddress`, `myDataBase`, `myUsername`, `myPassword`, `myTable` with your own values for your database setup.