This C# program demonstrates how to fill an entire SQL dataset with all of the table data in a database for Microsoft SQL in C#.
using System; using System.Data; using System.Data.SqlClient; namespace FillDataset { class Program { static void Main(string[] args) { // The using block ensures that the connection is closed when it exits this block. using (SqlConnection qConnection = new SqlConnection( @"Server=localhost\SQLEXPRESS01;Database=catholic;Trusted_Connection=True;")) { qConnection.Open(); DataSet qDataSet = new DataSet("catholic"); DataTable qDataTable = qConnection.GetSchema("Tables"); // Run through all of the tables in the database and store them in the dataset. foreach (DataRow qRow in qDataTable.Rows) { // The third entry, at index 2, is the table name using (SqlDataAdapter qAdapter = new SqlDataAdapter( "SELECT * FROM " + qRow[2], qConnection)) { qAdapter.Fill(qDataSet, qRow[2].ToString()); } } // The Dataset is filled with the tables and their data // Here, we output the data to demonstrate that it is in the dataset PrintDataset(qDataSet); } } static public void PrintDataset(DataSet qDataSet) { string sDataSet = String.Format("{0, 25}", qDataSet.DataSetName) + "\n"; // Run through the tables in the dataset foreach (DataTable qTable in qDataSet.Tables) { // Write the table name first sDataSet += String.Format("{0, 25}", qTable.TableName) + "\n"; // List the column names first foreach (DataColumn qColumn in qTable.Columns) { sDataSet += String.Format("{0,-25}", qColumn.ColumnName); } sDataSet += "\n"; sDataSet += "-------------------------------------------------\n"; foreach (DataRow qRow in qTable.Rows) { foreach (object qData in qRow.ItemArray) { sDataSet += String.Format("{0,-25}", qData); } sDataSet += "\n"; } sDataSet += "\n"; } Console.Write(sDataSet); } } }
catholic sacraments name category ------------------------------------------------- Baptism Initiation Eucharist Initiation Confirmation Initiation Penance Healing Anointing of the Sick Healing Holy Matrimony Service Holy Orders Service apostles name symbol ------------------------------------------------- John Chalice Andrew Transverse Cross Peter Keys Press any key to continue . . .
© 20072024 XoaX.net LLC. All rights reserved.