How to check for domain Constraints using oleDb? - c#

I have to find every columns that doesn't have a domain constraints in a database(MS Access) and for each one calculate min and max values to the current data and then to add from my program the corresponding constraint.
For example, a column "Foo" has the min value 0 and the max value 100,and I need the constraint "Foo between 0 And 100".
How can I check if a column has this constraint in C# ?
In access I found this at "Validation rules".
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Proiect
{
public partial class Form1 : Form
{
private OleDbConnection con = new OleDbConnection();
private new OleDbCommand cmd = new OleDbCommand();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.Carti'
this.cartiTableAdapter.Fill(this.dataSet1.Carti);
cartiTableAdapter.Fill(dataSet1.Carti);
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.ReadOnly = true;
con.ConnectionString="Provider=Microsoft.ACE.OLEDB.12.0;"+
"DataSource=D:\..\BD.accdb";
cmd.Connection=con;
this.cartiTableAdapter.Fill(this.dataSet1.Carti);
chkC.Checked=false;
}
private void chkC_CheckedChanged(object sender, EventArgs e)
{
}
}
}

For the purpose of checking the constrains applied on your table you are looking to use OleDbSchemaGuid.Check_Constraints Field. How to use this is actually a little bit different with how you would use per say OleDbSchemaGuid.Tables.
To help you on this I have written you a little console application that you can simply copy/paste on a new console application project in Visual Studio (or any preferred software) and run it to see how this works in action. The example is implemented on the famous Northwind database.
OleDbConnection cn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
//Open a connection to the SQL Server Northwind database.
// This is the sample DB I have used in my example.
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;";
cn.Open();
//Retrieve records from the Employees table into a DataReader.
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM Employees";
//Retrieve column schema into a constraints.
var schemaTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Check_Constraints,null);
//For each field in the table...
foreach (DataRow myField in schemaTable.Rows)
{
//For each property of the field...
foreach (DataColumn myProperty in schemaTable.Columns)
{
//Display the field name and value.
Console.WriteLine(myProperty.ColumnName + " = " + myField[myProperty].ToString());
}
Console.WriteLine();
//Pause.
}
Console.WriteLine("Done");
Console.ReadLine();
//Always close the DataReader and connection.
cn.Close();
and if you look at the output, you can see the constraint applied on the Discount field of Discount table.
CONSTRAINT_CATALOG = Northwind
CONSTRAINT_SCHEMA = dbo
CONSTRAINT_NAME = CK_Discount
CHECK_CLAUSE = ([Discount]>=(0) AND [Discount]<=(1))
DESCRIPTION =
Update
Also in general I will recommend you to get yourself familiar with How To Retrieve Column Schema by Using the DataReader GetSchemaTable Method and Visual C# .NET
The example below is the line by line copy of the code from link above except I have added a List of string to this code and captured the table's field name (called ColumnName in C# DataColumn in this context), and I have marked the lines I have added with // ++ Added ++.
OleDbConnection cn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
DataTable schemaTable;
OleDbDataReader myReader;
//Open a connection to the SQL Server Northwind database.
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=EINSTEINIUM\\SQL2014EXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;Encrypt=False;TrustServerCertificate=False";
cn.Open();
//Retrieve records from the Employees table into a DataReader.
cmd.Connection = cn;
cmd.CommandText = "SELECT * FROM Employees";
myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
//Retrieve column schema into a DataTable.
schemaTable = myReader.GetSchemaTable();
// ++ Added ++
var listOfTableFields = new List<string>();
//For each field in the table...
foreach (DataRow myField in schemaTable.Rows)
{
//For each property of the field...
foreach (DataColumn myProperty in schemaTable.Columns)
{
//Display the field name and value.
Console.WriteLine(myProperty.ColumnName + " = " + myField[myProperty].ToString());
// ++ Added ++
if (myProperty.ColumnName == "ColumnName")
{
listOfTableFields.Add(myField[myProperty].ToString());
}
}
Console.WriteLine();
//Pause.
}
//Always close the DataReader and connection.
myReader.Close();
cn.Close();
// ++ Added ++
Console.WriteLine("List of fields in Employees table.");
// List of Fields in the Employees table.
foreach (var fieldName in listOfTableFields)
{
Console.WriteLine(fieldName);
}
Console.ReadLine();
Paste this code in a Console app and learn how to use it. It will be very easy then to move the parts you need to the buttons OnClick.

Related

Get list of IDs from Access Database using OleDbDataReader

Using a Microsoft Access database for a Web App Quiz Manager, I have table with a ID column that has a list of IDs which looks something like this:
ID Answer QuesDescription QuesAnswer QuestionNum
1 1 Example Example 1
3 3 Example Example 2
4 4 Example Example 3
6 1 Example Example 4
Using the query SELECT ID FROM (QuizName) with OleDbCommand I managed to get the ID values from the database and stored into OleDbDataReader reader. But i don't know how to get the ID values from the reader and store them as a String List. Does anyone know how to do this?
I've tried using stuff like
public List<string> GetIDValueFromQuestionNumber(string quizNumber)
{
try
{
string strSQL = string.Concat("SELECT count(ID) as RowCount FROM ", quizNumber);
List<string> resourceNames = new List<string>();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
int rowCount = (int)reader["RowCount"];
strSQL = string.Concat("SELECT ID FROM ", quizNumber);
command = new OleDbCommand(strSQL, connection);
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
resourceNames.Add(" " + reader.GetString(0));
}
}
connection.Close();
for (int count = 0; count < rowCount; count++)
{
int value = (int)reader.GetValue(count);
resourceNames.Add(value.ToString());
}
}
return resourceNames;
}
catch (Exception e)
{
return null;
}
}
But to no luck.
I should note that these tables can vary in depth.
I suggest this approach.
Say a form - DataGridView to display our data.
And say a listbox to display the list of id that you build up into that List
So, this form:
And the button click code:
private void button1_Click(object sender, EventArgs e)
{
// load up our data list with Hotels
string strSQL =
#"SELECT ID, FirstName, LastName, City, HotelName
FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = MyRst(strSQL);
dataGridView1.DataSource = rstData;
// now build up a list of id in to string colleciton
List<string> MyIDList = new List<string>();
foreach (DataRow MyOneRow in rstData.Rows)
{
MyIDList.Add(MyOneRow["ID"].ToString());
}
// Lets set the id list to a listbox
listBox1.DataSource = MyIDList;
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL = new OleDbCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And now we get/see this:
So, pull the table. Display it, do whatever.
Then use the SAME table, and simple loop each row, grab the ID and add to your list.
And of course, one would probably hide the "id" in the above list (just add the columns using edit columns - only add the ones you want). You can still get/grab/use ANY column from the data source - it not a requirement to display such columns.

C# C0246 While Filtering DataGridView with Listbox whose items come from SQL Server

I share with you a piece of code that works except the part where I'm trying to loop in the items of my listbox. That's why I'm here asking you for some help.
Lately, I switched from VBA to C# so I'm still new on this and don't undertsand everything yet.
So, the below code connect to my SQL server DB and fetch data both within my listbox and a DataGridView. I can filter with two textboxes also.
So now I have items within my listbox and my db's view within the DataGridview. I'd like to filter my DataGridview (which is filled by a datatable ) with my Listbox's item. I miss only a silly part I guess. Why Do I get this CS0246 "ListItem could not be found"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsAppTest
{
public partial class Form1 : Form
{
//Initialize the component and display the items within my listbox CS_Bonds_listBox
public Form1()
{
InitializeComponent();
string connetionString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connetionString);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT DISTINCT RatingProvider FROM Bonds", conn);
adapter.Fill(ds);
this.CS_Bonds_listBox.DataSource = ds.Tables[0];
this.CS_Bonds_listBox.DisplayMember = "RatingProvider";
}
private void Form1_Load(object sender, EventArgs e)
{
}
DataTable dtTEST = new DataTable();
// Next, when clicking on my button Connect, I retrieve my db into a Datatable that is displayed within //the Datagridview1
private void buttonConnect_Click(object sender, EventArgs e)
{
string connetionString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
SqlConnection cnn= new SqlConnection(connetionString);
cnn.Open();
MessageBox.Show("Connection Open !");
String sql = "Select * from Bonds";
SqlCommand command = new SqlCommand(sql, cnn);
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = command;
sqlDA.Fill(dtTEST);
dataGridView1.DataSource = dtTEST;
cnn.Close();
}
private void ISIN_Bonds_textBox_TextChanged(object sender, EventArgs e)
{
DataView dv = dtTEST.DefaultView;
dv.RowFilter = "ISIN LIKE '" + ISIN_Bonds_textBox.Text + "%'";
dataGridView1.DataSource = dv;
}
private void Ticker_Bonds_textBox_TextChanged(object sender, EventArgs e)
{
DataView dv1 = dtTEST.DefaultView;
dv1.RowFilter = "Ticker LIKE '" + Ticker_Bonds_textBox.Text + "%'";
dataGridView1.DataSource = dv1;
}
private void CS_Bonds_listBox_SelectedIndexChanged(object sender, EventArgs e)
{
string conString = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
string query = "SELECT ISIN, Ticker, CrediSight, FROM Bonds";
string condition = string.Empty;
foreach (ListItem item in CS_Bonds_listBox.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : "";
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" WHERE Country IN ({0})", condition.Substring(0, condition.Length - 1));
}
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query + condition))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
//dataGridView1.DataBind();
}
}
}
}
}
}
}
This line has a problem:
foreach (ListItem item in CS_Bonds_listBox.Items)
A ListItem is a WebForms thing, and your application is a WinForms thing; your listbox doesn't contain a list of ListItem objects so this line of code wouldn't work out anyway, even if the relevant web namespace was imported.
Because you've bound your listbox to a datatable the list it is showing is full of DataRowView objects, so that's what you need to process. A DataRowView has a Row property that gives you the underlying row, which in turn can be accessed by a column name.
Additionally, to make your life easier a listbox has a SelectedItems property so you don't need to check every item for being selected:
foreach (DataRowView drv in CS_Bonds_listBox.SelectedItems)
{
var dr = drv.Row as DataRow;
var rp = dr["RatingProvider"];
condition += $"'{rp}',"
}
Your condition will end up with a trailing comma as a result of this, so trim it off before you build an IN clause with it:
condition = condition.TrimEnd(',');
This technique could be susceptible to SQL Injection hacking if the user manages to change the text showing in the list items.
A better way to handle the problem is via parameterization. You'd do it like this:
var cmd = new SqlCommand("SELECT * FROM table WHERE Country IN(", connStr);
int i = 0;
foreach (DataRowView drv in CS_Bonds_listBox.SelectedItems)
{
var dr = drv.Row as DataRow;
var rp = dr["RatingProvider"];
cmd.CommandText += $"#p{i},";
cmd.Parameters.Add($"#p{i}", SqlDbType.VarChar).Value = rp;
i++;
}
cmd.CommandText = cmd.CommandText.TrimEnd(',') + ")";
using(var da = new SqlDataAdapter(cmd))
{
var dt = new DataTable();
da.Fill(dt);
someGridView.DataSource = dt;
}
This builds an sql that looks like SELECT * FROM table WHERE Country IN(#p0,#p1,#p2.... i.e. we have concatenated parameter placeholders in rather than concatenating values in. At the same time we have filled the parameters collection with the parameter values
It also means that our database can't be hacked via our program, and our app doesn't die in a heap when the user selects a country with a name like Cote d'Ivoire
Some other things to note to tidy your code up:
SqlDataAdapter can take a string SQL and a string connection-string. You don't need to make a SqlCommand for it. You don't need to open and close conenctions for it; it knows how to do all this itself. I only used a SqlCommand because I was building the parameters collection as I went. Ordinarily I'd do using(var da = SqlDataAdapter("SELECT...", "Server=..") because it makes things nice and tidy.
This means e.g. your constructor can be simply:
//put this here once
private string _connStr = #"Data Source=my_server;Initial Catalog=my_db;Integrated Security=SSPI";
public Form1()
{
InitializeComponent();
var dt = new DataTable();
using(var da = new SqlDataAdapter("SELECT DISTINCT RatingProvider FROM Bonds", _connStr))
adapter.Fill(dt);
this.CS_Bonds_listBox.DataSource = dt;
this.CS_Bonds_listBox.DisplayMember = "RatingProvider";
}

How can we import excel file to Sql server table where excel table columns are not in order as Sql table

I have an excel file whose worksheets name same as SQL table name but the column mapping is failing as both have same columns but the order of columns are different , please help me on this.
Edited: Added another example at the end.
One of many ways of implementing what you ask is to import worksheet as a datatable in c# and then Insert the data with SqlBulkCopy (SqlBulkCopy (MSDN)). This method is better for large files because SqlBulkCopy uses bulk insert command.
For the first step (import file as datatable) you have many options such as using OLEDB for xls or xlsx (you can use my example or others such as this link or this), using third-party libraries such as easyxls.
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection ;
System.Data.DataSet DtSet ;
System.Data.OleDb.OleDbDataAdapter MyCommand ;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
}
}
After that for second step you can use SQLBulkCopy with column mapping to map the dataTable columns to your database table columns.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoDifferentColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Set up the bulk copy object.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoDifferentColumns";
// Set up the column mappings by name.
SqlBulkCopyColumnMapping mapID =
new SqlBulkCopyColumnMapping("ProductID", "ProdID");
bulkCopy.ColumnMappings.Add(mapID);
SqlBulkCopyColumnMapping mapName =
new SqlBulkCopyColumnMapping("Name", "ProdName");
bulkCopy.ColumnMappings.Add(mapName);
SqlBulkCopyColumnMapping mapMumber =
new SqlBulkCopyColumnMapping("ProductNumber", "ProdNum");
bulkCopy.ColumnMappings.Add(mapMumber);
// Write from the source to the destination.
try
{
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
private static string GetConnectionString()
// To avoid storing the sourceConnection string in your code,
// you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
"Initial Catalog=AdventureWorks;";
}
}
another example of SqlBulkCopy usage:
public bool CopyTransactionDataToTable(DataTable Dt, long ProductID)
{
try
{
SqlBulkCopy copy = new SqlBulkCopy(Adapter.GetActiveConnection().ConnectionString);
Collection = mapping.LoadMappedNameEntityByProductID(ProductID);
copy.ColumnMappings.Add("ProductID", "ProductID");
copy.ColumnMappings.Add("ResellerID", "ResellerID");
copy.ColumnMappings.Add("Status", "Status");
copy.ColumnMappings.Add("PK_ID", "TxID");
copy.DestinationTableName = "TBLProdect";
copy.BulkCopyTimeout = ConfigurationSettings.AppSettings.Get(UIConstants.SQLTimeOut).ToInt32();
copy.WriteToServer(Dt);
Adapter.CommandTimeOut = copy.BulkCopyTimeout;
return true;
}
catch (Exception ex)
{
Log.Error(ex);
return false;
}
}
You didn't indicate if you were looking to make this repetitive, or programmatic, etc - but two other options would be to use the SQL Server Data Import/Export Wizard
https://msdn.microsoft.com/en-us/library/ms141209.aspx
Another option would be to use SQL Server Integration Services (SSIS)
http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/

Inserting data from CSV in mutiple tables via ASP.NET (C#), SQL Server

I have an CSV file with 7 columns, which a user has to upload so it can be added in the database.
I found some help in reading the CSV and putting all the info in a single table, however, the data has to be spread over three tables.
My code for inserting all the data to 1 table:
protected void Upload(object sender, EventArgs e)
{
//Upload and save the file
string csvPath = Server.MapPath("~/Temp/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(csvPath);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[7] {
new DataColumn("Title", typeof(string)),
new DataColumn("Artist", typeof(string)),
new DataColumn("Years", typeof(string)),
new DataColumn("Position", typeof(string)),
new DataColumn("Senddate", typeof(string)),
new DataColumn("Sendfrom", typeof(string)),
new DataColumn("Sendtill", typeof(string))});
string csvData = File.ReadAllText(csvPath);
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(';'))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
string consString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.ingevoerd";
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
As you can see, it takes 7 columns, and puts them in the table [dbo].[ingevoerd]
How can i split the data to put the column 'Title' and 'Years' in a table called Song, 'Artist' in a table called Artiest, and 'Position', 'Senddate', 'Sendfrom' an 'Sendtill' in a table called Lijst?
For more information, put down a comment.
imho this is not the best way to handle this upload because the content is not flat data you can bulk upload in a breeze; there are many entitiest (at least 3) that should be linked.
i would go with the 'old style' approach of calling a insert for each row with proper parameters.
you are already looping through the Whole recordset when reading the CSV so i would make something like:
protected void Upload(object sender, EventArgs e)
{
//Upload and save the file
string csvPath = Server.MapPath("~/Temp/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(csvPath);
string consString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
con.Open();
using (SqlTransaction tran = con.BeginTransaction())
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.Transaction = tran;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "your_sp_name_here";
cmd.Parameters.Add(new SqlParameter("#title",System.Data.SqlDbType.NVarChar));
cmd.Parameters.Add(new SqlParameter("#artist", System.Data.SqlDbType.NVarChar));
// other parameters follow
// ...
string csvData = File.ReadAllText(csvPath);
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
// for every row call the command and fill in the parameters with proper values
cmd.Parameters["#title"].Value = row[0];
cmd.Parameters["#artist"].Value = row[1];
// ...
cmd.ExecuteNonQuery();
}
}
// when done commit the transaction
tran.Commit();
}
}
}
inside your stored procedure handle the 'split' of the data in the relevant tables taking all the steps required to avoid duplicates and maybe linking the data among the tables:
create procedure your_sp_name_here(#title nvarchar(50), #artist nvarchar(50), #year int)
as
begin
-- add logic & checks here if needed
-- ...
-- ...
-- if everything is ok insert the rows
insert into songs (title, year) values (#title, #year)
insert into Artiest (Artist) values (#artist)
end
Have you looked into column mappings?
Check out stackoverflow.com/questions/17469349/mapping-columns-in-a-datatable-to-a-sql-table-with-sqlbulkcopy

How to insert multiple list in SQL Server 2008 using c#?

My table contains 10 columns. I need to insert a list using c#.
I have stored the details of multiple members, for each count its has to insert the consecutive details in the same row.
if (members.Count >= 1)
{
foreach (Members myList in members)
{
Command.Parameters.Add("first", SqlDbType.VarChar).Value = myList.first;
Command.Parameters.Add("last", SqlDbType.VarChar).Value = myList.last;
Command.Parameters.Add("age", SqlDbType.VarChar).Value = myList.age;
}
}
Example : for count=1 the table looks like
"fName1","lName1",21
for count=2 the table looks like
"fName1","lName1",21,"fname2","lName2",21
please help on this.
The coding style looks ambiguous. Your foreach loop runs for - 'Members' in members. It makes hard to understand what are trying to do. Let me suggest you to refactor your code and let the class name be 'Member'. You can put members in db with ADO.Net (there are other ways too) as follows -
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
//select just schema of the table.
command.CommandText = "select * from members where 1=2;";
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
using (SqlCommandBuilder builder = new SqlCommandBuilder(adapter))
{
using (DataTable dt = new DataTable())
{
foreach (Member item in memebers)
{
DataRow row = dt.NewRow();
row.SetField<string>("", item.FirstName);
row.SetField<string>("", item.LastName);
row.SetField<int>("", item.Age);
//
// number of SetField should be equal to number of selected columns.
//
dt.Rows.Add(row);
}
adapter.Update(dt);
}
}
}
}
}

Categories

Resources