且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据C#中的数据集表将数据插入到sql表中

更新时间:2023-01-29 08:55:39

阅读本文: http://***.com/questions/6093007/copying-data-from-datatable-to-sql-server [ ^ ]


DataSet ds = new DataSet(); // Assign your DataSet object here
Dictionary<string, object> parameters;
List<string> sqlQuery = new List<string>();
// Write your SQL Query or Procedure Name in this list aganist each table.
// For example:
// For Table 1 the Query is: INSERT INTO Emp(FName, LName, Sal) VALUES(@FName, @LName, @Sal)
// For Table 2 the Query is: INSERT INTO Stu(FName, LName, Marks) VALUES(@FName, @LName, @Marks)
// Then you should add like following way:
sqlQuery.Add("INSERT INTO Emp(FName, LName, Sal) VALUES(@FName, @LName, @Sal)");
sqlQuery.Add("INSERT INTO Stu(FName, LName, Marks) VALUES(@FName, @LName, @Marks)");
// NOTE: you should add the query in the same order as the tables are in the DataSet
// That Means You have to follow the order (during adding sql query in the list) of adding DataTables in the DataSet respectively.
for(int i=0; i<ds.Tables.Count; i++)
{
	DataTable dt = ds.Tables[i];
	parameters = new Dictionary<string, object>();
	foreach (DataRow dr in dt.Rows)
	{
		for (int j = 0; j < dt.Columns.Count; j++)
			parameters.Add("@" + dt.Columns[j].ColumnName, dr[j]);
	}
	InsertUpdateDelete(sqlQuery[i], parameters, false);
}

/// <summary>
/// Insert, Update and Delete in the database through this method
/// </summary>
/// <param name="sql">The SQL Query or the name of the Stored Procedure</param>
/// <param name="parameters">The values which you have to insert, update, or delete</param>
/// <param name="isProcedure">If the first parameter "sql" is any name of the stored procedure then it must be true</param>
/// <returns>True for successful execution, otherwise False</returns>
public bool InsertUpdateDelete(string sql, Dictionary<string, object> parameters, bool isProcedure)
{
	using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
	{
		sqlConnection.Open();

		using (SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection))
		{
			if (isProcedure) sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
			else sqlCommand.CommandType = System.Data.CommandType.Text;

			// Adding parameters using Dictionary...
			foreach (KeyValuePair<string, object> parameter in parameters)
				sqlCommand.Parameters.Add(new SqlParameter(parameter.Key, parameter.Value));
			if (sqlCommand.ExecuteNonQuery() > 0) return true;
			else return false;
		}
	}
}