CSV file filled in data adapter is empty or not - csv

private DataTable GetDataFromCSV()
{
System.Data.DataTable dtExecChanges = new System.Data.DataTable("exec_changes");
string dirName = Path.GetDirectoryName(sInputFileName);
using (OleDbConnection cn =
new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;" +
"Data Source=" + dirName + ";" +
"Extended Properties=\"Text;HDR=Yes;FMT=Delimited\""))
{
// Open the connection
cn.Open();
// Set up the adapter
using (OleDbDataAdapter adapter =
new OleDbDataAdapter("SELECT * FROM " + (sInputFileName.Substring(sInputFileName.LastIndexOf("\\") + 1)), cn))
{
adapter.Fill(dtExecChanges);
}
cn.Close();
}
When I fill my data table dtExecChanges it will error coz my CSV file is empty.
Is there a way to chck is the select query is actually fetching any rows b4 filling by data table??

Related

how to display 2 tables from mysql in visual studio 17

this is in my controller
string connStr = "server=" + IpAddress + ";user=" + UserName + ";database=" + DatabaseName + ";port=" + PortNumber + ";password=" + Password + ";SslMode=none;";
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string query = " select * from Cities,Regions";
MySqlCommand com = new MySqlCommand(query, conn);
MySqlDataAdapter da = new MySqlDataAdapter(com);
DataTable ds = new DataTable();
da.Fill(ds);
conn.Close();
I use a view model for displaying data from mysql and i fill them as below.
List<Models.ViewModels.city> CT = new List<Models.ViewModels.city>();
SftpClient sftpclient = new SftpClient("port", "root", "name");
sftpclient.Connect();
foreach (DataRow item in ds.Rows)
{
city ct = new city
{
CityName = item.itemArray[1].ToString(),
CityNumber = Convert.ToInt32(item.itemArray[2])
}
region rg = new region
{
RegionName = item.itemArray[1].ToString(),
RegionNumber = Convert.ToInt32(item.itemArray[2])
}
}
CT.Add(ct);
return View(CT.ToList());
How could i show regions in my razor. i already used viewbag for sending a list form my region viewmodel. but it doesn't fill the viewmodel obviously but how should i fill the region viewmodel

asp.net:query with multiple where conditions

1. I have query.But couldn't add second where condition.Please suggest me the correct semantic .
2. And how can fetch the data from dropdownlist and show it in gridview.
3. How can i fetch value from Tution fee Column of my database when condition satisfies ,and Hostel Fee on fail of condition.??
protected void BindGridview()
{
constr = ConfigurationManager.ConnectionStrings["connstring_DETMIS"].ToString(); // connection string
// String FID = DropDownList1.SelectedItem.Value;
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(constr)) {
conn.Open();
using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" + " where F_id =" + DropDownList1.SelectedItem.Value " and C_id=" + DropDownList2.SelectedItem.Value, conn)) {
using (var reader = cmd.ExecuteReader()) {
if (reader.HasRows) {
gvDetails.DataSource = reader;
gvDetails.DataBind();
} else
lblWarning.Text = "There are no records..";
}
}
}
}
Welcome to Stackoverflow. You should first research on the google as why you are not able to add multiple conditions(It's just because of simple syntax mistake).
The exact code of line would be something like this.
using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" +
" where F_id = '" + DropDownList1.SelectedItem.Value + "' and C_id=" + DropDownList2.SelectedItem.Value + "'", conn))
NOTE:- As a fellow developer, I won't suggest you to do this by passing values from here as it is dangerous and prone to SQL INJECTION
I would rather tell you to go by using Parameterized queries
Hope that helps and for future go for the Parametrized ones, as it is easy and technically preffered.
protected void BindGridview()
{
String strConnString = ConfigurationManager
.ConnectionStrings["connstring_DETMIS"].ConnectionString;
String strQuery = "select * from student_details " +
"where F_id=#F_Id and C_id=#C_Id";
MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(strConnString);
MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Parameters.AddWithValue("#F_Id",
DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("#C_Id",
DropDownList2.SelectedItem.Value);
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
try
{
con.Open();
gvDetails.DataSource = cmd.ExecuteReader();
gvDetails.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}

Parse MS Excel files dynamically with SSIS

I have a business requirement that is looking for the ability to have Excel files placed in a network location and the data from these files uploaded to a SQL Server database. The files will contain 1 worksheet of data. The files correspond to a table found within a known database. The files can and will correlate to multiple tables and will be known only when opening up the file, i.e., the name of the worksheet. I'm currently creating multiple SSIS packages for each of these files as they are uploaded to the shared drive but sometimes, I'm not creating the package fast enough.
I guess my question is, is this type of dynamic parsing something that SSIS can accomplish from a Script Task within a Foreach container? or should I look into another option?
So far, I have the following...but as I've researched, I've come across post similar to this: Extracting excel files with SSIS and that is making me slightly concerned regarding the feasiability...
public void Main()
{
// TODO: Add your code here
Dts.TaskResult = (int)ScriptResults.Success;
string NetworkLocation;
//Create database connection
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(Dts.Connections["db"].AcquireConnection(Dts.Transaction) as SqlConnection);
//Obtain the location of the file(s)
NetworkLocation = (string)Dts.Variables["User::NetworkLocation"].Value;
string[] dirs = Directory.GetFiles(NetworkLocation, "*.csv");
}
So, any thoughts or ideas or what direction I should look into?
I wrote a SSIS package a few months ago that does exactly what you seek, plus a little more. In my case, several hundred Excel files containing one or more worksheets of differing names needed to be imported into a database as unique staging tables. Also, the column names and number of columns in each worksheet were unknown. Each worksheet became its own table and the table name was a combination of the original Excel file name and the worksheet name (FileName__WorksheetName). I applied two underscores between the file name and worksheet name in case the file and worksheet names contained underscores. There are a few caveats to this process: 1) All of the Excel files must be located in the same folder; 2) The column headers in each worksheet must appear in the first row; and 3) the worksheet names must not contain any special characters (spaces are automatically replaced with an underscore).
Steps:
1) Create a For Each Loop Container. Under Collection, apply a "Foreach File Enumerator" where under Enumerator configuration, list the folder location and the Files. For files you can list . or even *.xlsx or *.xls to filter to specific files. Apply Fully Qualified. For Variable Mappings, apply a string user variable like "ExcelFile" with an index of 0.
2) Add a Script task in the For Each Loop Container. You will send it the ReadOnlyVariable "ExcelFile" and it will write to two new string variables "TableName" and "Worksheets" under ReadWriteVariables. Apply the following C# script. Note, scince the following script will update your Excel files, you should be applying copies of your originals.
#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Xml.Serialization;
#endregion
namespace xxxxxxxxx
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
// Includes full path, filename and extension... C:\Documents\ThisExcel.xlsx
string xlFile = Dts.Variables["User::ExcelFile"].Value.ToString();
// Remove path changing value to "ThisExcel.xlsx"
string NoPath = Path.GetFileName(xlFile);
// Remove extension changing value to "ThisExcel".
// This is applied because filename will become part of the name for new database tables
string tableName = Path.GetFileNameWithoutExtension(NoPath);
// Replace any spaces with underscores in tableName (FileName without path and extension)
tableName = tableName.Replace(" ", "_");
Dts.Variables["User::TableName"].Value = tableName;
Excel.Application app = new Excel.Application();
Excel.Workbook excelWorkbook;
try
{
excelWorkbook = app.Workbooks.Open(xlFile);
string tempsheet = " ";
int CountWorksheets = excelWorkbook.Sheets.Count;
//Dts.Variables["User::WorksheetCount"].Value = CountWorksheets;
string[] Excelworksheets;
Excelworksheets = new string[CountWorksheets];
int x = 0;
// Rename worksheets replace empty space with an underscore needed for an SSIS import and
// to avoid empty spaces in final table names.
foreach (Excel.Worksheet sheet in excelWorkbook.Worksheets)
{
tempsheet = sheet.Name;
tempsheet = tempsheet.Replace(" ", "_");
Excelworksheets[x++] = tempsheet.ToString();
sheet.Name = tempsheet;
}
Dts.Variables["User::Worksheets"].Value = Excelworksheets;
excelWorkbook.Save();
excelWorkbook.Close();
}
catch (Exception ex)
{
MessageBox.Show("Excel sheet rename failed for file " + xlFile + " based on " + ex.Message);
}
finally
{
app.Quit();
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
3) After saving and building the above C# script task, add a For Each Loop Container in the earlier For Each Loop container below the script task just created. This will loop through each worksheet in each Excel file. If you only have one worksheet, that is fine. It will apply an Enumerator of "Foreach From Variable Enumerator", which will be the "Worksheets" string variable created that is populated in the before mentioned script task. It will write to a new user string variable called "Worksheet" with an Index of 0.
4) Within this new nested For Each Loop Container, add script task that will create the database table for each worksheet. The tricky part I had to deal with here was defining the field types, this is not retained from the Excel worksheets or text CSV files. So I made them all nvarchar(255) or, if column headers were something like Remark, Description or something else, I made it nvarchar(max), which is good to 4000 or 4262 characters (I do not recall for certain). Here is the dynamic code I applied stemming from what you began.
#region Namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
using System.Xml.Serialization;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
#endregion
namespace yyyyyyyyyy
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
public void Main()
{
// TODO: Add your code here
string xlFile = Dts.Variables["User::ExcelFile"].Value.ToString(); //Includes full path and filename with extension
//xlFilex = xlFilex.Replace(#"\", #"\\");
string worksheet = Dts.Variables["User::Worksheet"].Value.ToString(); //Worksheet name from Excel file.
string Tablename = Dts.Variables["User::TableName"].Value.ToString(); //Currently file name without path and extension. Spaces replaced by underscores.
string ExcelExtension = Path.GetExtension(xlFile);
string columnName = "";
string columnType = "";
int i = 0;
string worksheet2 = worksheet + "$";
OleDbConnection xl = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + xlFile + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");
xl.Open();
System.Data.DataTable dt = xl.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, worksheet2, null });
List<string> listColumn = new List<string>();
// Create the name of the table that will be created in the SQL Server database, which is
// a concatentation of the root file name and worksheet name separated by two undescores.
Tablename = Tablename + "__" + worksheet;
string CreateTable = "CREATE TABLE " + Tablename + " (";
string InsertTable = "INSERT INTO " + Tablename + " (";
string SelectColumns = "";
// Create the string that will be applied to create the table defining the field types based on the names
foreach (DataRow row in dt.Rows)
{
listColumn.Add(row["Column_name"].ToString());
columnName = listColumn[i].ToString();
if ((columnName == "Remark") || (columnName == "remark") || (columnName == "REMARK") ||
(columnName == "Remarks") || (columnName == "remarks") || (columnName == "REMARKS") ||
(columnName.Contains("Remarks")) || (columnName.Contains("remarks")) || (columnName.Contains("REMARKS")) ||
(columnName.Contains("Remark")) || (columnName.Contains("remark")) || (columnName.Contains("REMARK")) ||
(columnName == "Comment") || (columnName == "comment") || (columnName == "COMMENT") ||
(columnName == "Comments") || (columnName == "comments") || (columnName == "COMMENTS") ||
(columnName == "Description") || (columnName == "description") || (columnName == "DESCRIPTION") ||
(columnName.Contains("Description")) || (columnName.Contains("description")) || (columnName.Contains("DESCRIPTION")) ||
(columnName == "Legal") || (columnName == "legal") || (columnName == "LEGAL") ||
(columnName == "Note") || (columnName == "note") || (columnName == "NOTE") ||
(columnName.Contains("Format")) || (columnName.Contains("format")) || (columnName.Contains("FORMAT")) ||
(columnName == "Notes") || (columnName == "notes") || (columnName == "NOTES")
)
{
columnType = "nvarchar(max),";
}
else
{
columnType = "nvarchar(255),";
}
CreateTable = CreateTable + "[" + columnName + "] " + columnType;
InsertTable = InsertTable + "[" + columnName + "],";
SelectColumns = SelectColumns + "[" + columnName + "],";
//MessageBox.Show(columnName + " " + columnType);
i++;
}
// Remove last comma from CreateTable and add closing
CreateTable = CreateTable.Remove(CreateTable.Length - 1);
CreateTable = CreateTable + ")";
// Removoe last comman from InsertTable and add closing
InsertTable = InsertTable.Remove(InsertTable.Length - 1);
InsertTable = InsertTable + ")";
// Removoe last comman from SelectColumns
SelectColumns = SelectColumns.Remove(SelectColumns.Length - 1);
xl.Close();
string SQL = "";
// Assemble the dynamic SQL that will be applied in the SQL task next to generate and populate a new database table
if (ExcelExtension == ".xlsx")
{
SQL = "IF OBJECT_ID ('dbo." + Tablename + "') IS NOT NULL DROP TABLE dbo." + Tablename +
" " + CreateTable + " " +
InsertTable + " " + "SELECT " + SelectColumns + " FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', " +
//" INSERT INTO [dbo].[" + Tablename + "] SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', " +
"'Excel 12.0 Xml;HDR=YES;Database=" + xlFile + "', 'SELECT * FROM [" + worksheet + "$]');";
}
else if (ExcelExtension == ".xls")
{
SQL = "IF OBJECT_ID ('dbo." + Tablename + "') IS NOT NULL DROP TABLE dbo." + Tablename +
" " + CreateTable + " " +
" INSERT INTO [dbo].[" + Tablename + "] SELET * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', " +
"'Excel 8.0 Xml;HDR=YES;Database=" + xlFile + "', 'SELECT * FROM [" + worksheet + "$]');";
}
//MessageBox.Show(SQL);
Dts.Variables["User::CreateTableSQL"].Value = SQL;
Dts.TaskResult = (int)ScriptResults.Success;
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Looking at the above script you'll notice that the following ReadOnlyVariables will need to be declared: ExelFile, SourceFolder, TableName, tempFileName, and Worksheet. Then the following ReadWriteVariables will need to be declared: ColumnCount, CreateTable, and InsertTableName.
5) Within the nested ForEach Loop Container and just below the above Task script, add an Execute SQL Task that will run the sql contained in the CreateTableSQL variable. Be sure to set the SQLSourceType to "Variable". This will create and populate the table and even overwrite it if it already exists.
When done, you should have something that looks like the following flow:
Hope this helps and let me know if you have any questions. I did not have time to remove the extraneous stuff, but this should put you on the right path. This loop container is for Excel files, but you can add on other loop containers with code modified to handle CSV or other file types. All of this can be enclosed in a single SSIS package.
The final SQL task just runs the following TSQL that looks for field names in your database containing a space between words and replaces that space with an underscore. It is not necessary, but avoids having to apply SQL with columns wrapped with brackets [].
DECLARE My_Cursor Cursor
FOR
SELECT 'sp_rename '''+table_name+'.['+column_name+']'','''+replace(column_name,' ','_')+''',''COLUMN'''
FROM information_schema.columns
WHERE column_name like '% %'
OPEN My_Cursor
DECLARE #SQL NVARCHAR(1000)
FETCH NEXT FROM My_Cursor INTO #SQL
WHILE ##FETCH_STATUS <> -1
BEGIN
EXECUTE sp_executesql #SQL
FETCH NEXT FROM My_Cursor INTO #SQL
END
CLOSE My_Cursor
DEALLOCATE My_Cursor

import csv and xls for bulk upload of user to register in a website

i am developing a website and i want to register the school children in a bulk way as they will provide the excel sheet and want that when i upload that sheet it automatically register user in userinfo table
here is the code
if (Request.Files["FileUpload1"] != null && Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224446;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Planetskool-20130901224446.mdf;Database=DefaultConnection; Trusted_Connection=true;Persist Security Info=True";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [UserInfoID],[UserID],[GraphID],[UserLevelEnumId],[Title],[FirstName],[MiddleName],[LastName],[Birthdate],[Gender],[Email],[MobileNo],[Country],[Zipcode],[CountFollowers],[CountFollows],[CountFiles],[CountPhotos],[Quote],[AvatarURL],[isVerified],[VerificationCount],[UserEnumType],[UserCreatorId] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
//Give your Destination table name
sqlBulk.DestinationTableName = "UserInfo";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
// SQL Server Connection String
}
return RedirectToAction("Import");
your code like below
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
// Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there.
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
Debug.Write("SheetTitle = " + excelSheets[t]);
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
DataSet ds = new DataSet();
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
{
}
}

Bulk Insert into SQL Server 2008

for (int i = 0; i < myClass.Length; i++)
{
string upSql = "UPDATE CumulativeTable SET EngPosFT = #EngPosFT,EngFTAv=#EngFTAv WHERE RegNumber =#RegNumber AND Session=#Session AND Form=#Form AND Class=#Class";
SqlCommand cmdB = new SqlCommand(upSql, connection);
cmdB.CommandTimeout = 980000;
cmdB.Parameters.AddWithValue("#EngPosFT", Convert.ToInt32(Pos.GetValue(i)));
cmdB.Parameters.AddWithValue("#RegNumber", myClass.GetValue(i));
cmdB.Parameters.AddWithValue("#EngFTAv", Math.Round((engtot / arrayCount), 2));
cmdB.Parameters.AddWithValue("#Session", drpSess.SelectedValue);
cmdB.Parameters.AddWithValue("#Form", drpForm.SelectedValue);
cmdB.Parameters.AddWithValue("#Class", drpClass.SelectedValue);
int idd = Convert.ToInt32(cmdB.ExecuteScalar());
}
assuming myClass.Length is 60. This does 60 update statements. How can I limit it to 1 update statement. Please code example using the above code will be appreciated. Thanks
Tried using this
StringBuilder command = new StringBuilder();
SqlCommand cmdB = null;
for (int i = 0; i < myClass.Length; i++)
{
command.Append("UPDATE CumulativeTable SET" + " EngPosFT = " + Convert.ToInt32(Pos.GetValue(i)) + "," + " EngFTAv = " + Math.Round((engtot / arrayCount), 2) +
" WHERE RegNumber = " + myClass.GetValue(i) + " AND Session= " + drpSess.SelectedValue + " AND Form= " + drpForm.SelectedValue + " AND Class= " + drpClass.SelectedValue + ";");
//or command.AppendFormat("UPDATE CumulativeTable SET EngPosFT = {0},EngFTAv={1} WHERE RegNumber ={2} AND Session={3} AND Form={4} AND Class={5};", Convert.ToInt32(Pos.GetValue(i)), Math.Round((engtot / arrayCount), 2), myClass.GetValue(i), drpSess.SelectedValue, drpForm.SelectedValue, drpClass.SelectedValue);
}//max length is 128 error is encountered
Look at the BULK INSERT T-SQL command. But since I don't have a lot of personal experience with that command, I do see some immediate opportunity to improve this code using the same sql by creating the command and parameters outside of the loop, and only making the necessary changes inside the loop:
string upSql = "UPDATE CumulativeTable SET EngPosFT = #EngPosFT,EngFTAv=#EngFTAv WHERE RegNumber =#RegNumber AND Session=#Session AND Form=#Form AND Class=#Class";
SqlCommand cmdB = new SqlCommand(upSql, connection);
cmdB.CommandTimeout = 980000;
//I had to guess at the sql types you used here.
//Adjust this to match your actual column data types
cmdB.Parameters.Add("#EngPosFT", SqlDbType.Int);
cmdB.Parameters.Add("#RegNumber", SqlDbType.Int);
//It's really better to use explicit types here, too.
//I'll just update the first parameter as an example of how it looks:
cmdB.Parameters.Add("#EngFTAv", SqlDbType.Decimal).Value = Math.Round((engtot / arrayCount), 2));
cmdB.Parameters.AddWithValue("#Session", drpSess.SelectedValue);
cmdB.Parameters.AddWithValue("#Form", drpForm.SelectedValue);
cmdB.Parameters.AddWithValue("#Class", SqlDbTypedrpClass.SelectedValue);
for (int i = 0; i < myClass.Length; i++)
{
cmdB.Parameters[0].Value = Convert.ToInt32(Pos.GetValue(i)));
cmdB.Parameters[1].Value = myClass.GetValue(i));
int idd = Convert.ToInt32(cmdB.ExecuteScalar());
}
It would be better in this case to create a stored procedure that accepts a Table Valued Parameter. On the .NET side of things, you create a DataTable object containing a row for each set of values you want to use.
On the SQL Server side of things, you can treat the parameter as another table in a query. So inside the stored proc, you'd have:
UPDATE a
SET
EngPosFT = b.EngPosFT,
EngFTAv=b.EngFTAv
FROM
CumulativeTable a
inner join
#MyParm b
on
a.RegNumber =b.RegNumber AND
a.Session=b.Session AND
a.Form=b.Form AND
a.Class=b.Class
Where #MyParm is your table valued parameter.
This will then be processed as a single round-trip to the server.
In such scenarios it is always best to write a Stored Procedure and call that stored proc in the for loop, passing the necessary arguments at each call.
using System;
using System.Data;
using System.Data.SqlClient;
namespace DataTableExample
{
class Program
{
static void Main(string[] args)
{
DataTable prodSalesData = new DataTable("ProductSalesData");
// Create Column 1: SaleDate
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "SaleDate";
// Create Column 2: ProductName
DataColumn productNameColumn = new DataColumn();
productNameColumn.ColumnName = "ProductName";
// Create Column 3: TotalSales
DataColumn totalSalesColumn = new DataColumn();
totalSalesColumn.DataType = Type.GetType("System.Int32");
totalSalesColumn.ColumnName = "TotalSales";
// Add the columns to the ProductSalesData DataTable
prodSalesData.Columns.Add(dateColumn);
prodSalesData.Columns.Add(productNameColumn);
prodSalesData.Columns.Add(totalSalesColumn);
// Let's populate the datatable with our stats.
// You can add as many rows as you want here!
// Create a new row
DataRow dailyProductSalesRow = prodSalesData.NewRow();
dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
dailyProductSalesRow["ProductName"] = "Nike";
dailyProductSalesRow["TotalSales"] = 10;
// Add the row to the ProductSalesData DataTable
prodSalesData.Rows.Add(dailyProductSalesRow);
// Copy the DataTable to SQL Server using SqlBulkCopy
using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
{
dbConnection.Open();
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
{
s.DestinationTableName = prodSalesData.TableName;
foreach (var column in prodSalesData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.WriteToServer(prodSalesData);
}
}
}
}
}