How to insert multiple data into database? - c#

i would like to insert multiple data into my database. I am using for-each statement to get the data and when i insert into the database, it generates 10(just a random no. depending on the no. of data i retrieved) rows for me with one data in every row instead of all in one row. here is the for-each statement i am using.
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + kiev.Key + " ) VALUES ( '" + kiev.Value + "' ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();
}
}

There are better options like "SqlBulkCopy" available as already mentioned in the comments but also something like this should work:
string tablename = "";
string values = "";
string keys = "";
foreach(var kiev in dict)
{
string na = kiev.Key;
if(na != "db_table_name")
{
keys += kiev.Key + ", ";
values += "'" + kiev.Value + "', ";
}
}
keys = keys.Remove(keys.Length - 2);
values = values.Remove(values.Length - 2);
string quer = "insert into " + HttpContext.Current.Session["tablename"].ToString() + " ( " + keys + " ) VALUES ( " + values + " ) ";
SqlCommand cl = new SqlCommand(quer, con);
cl.ExecuteNonQuery();

Related

Inserting Multiple selected Listbox items into the same cell in SQL table

I want to insert multiple list box items into a a cell In SQL table with a comma dividing the items. The code posted below will only add the first selected item within a listbox. Hence If you select 2 or 10 items the first one u selected will be Inserted into the table. The for loop is my problem, I need to get all the selected values.
Thanks
protected void pg_upload_Click(object sender, EventArgs e)
{
using (SqlConnection mycon = new SqlConnection(connectionstring))
{
using (SqlCommand mycmd = mycon.CreateCommand())
{
if (textbox_make.Text == string.Empty || textbox_number.Text == string.Empty)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('The Make/Model and Number must be Entered')", true);
}
else
{
string str = "";
for (int i=0; i<= listbox_software.Items.Count; i++)
{
str = listbox_software.SelectedItem.ToString();
}
mycon.Open();
mycmd.CommandText = "INSERT INTO tbl_PG (Model, PGNumber, AssetNo, Area, Owner,IPAddress, SerialNo, OSVersion, Memory, Software) " +
"Values ('" + textbox_make.Text + "' , '" + textbox_number.Text + "' , '" + textbox_asset.Text + "' , '" + drop_area.Text + "' , '" + drop_owner.Text + "' , '" + textbox_ip.Text + "' " +
", '" + textbox_serial.Text + "' , '" + textbox_os.Text + "' , '" + textbox_memory.Text + "' , '" + str + "')";
mycmd.ExecuteNonQuery();
PopulateGridView();
lblsuscessmessage.Text = "Selected Record Added";
lblerrormessage.Text = "";
textbox_make.Text = string.Empty;
textbox_number.Text = string.Empty;
textbox_asset.Text = string.Empty;
textbox_ip.Text = string.Empty;
textbox_serial.Text = string.Empty;
textbox_os.Text = string.Empty;
textbox_memory.Text = string.Empty;
}
}
}
}
Add following namespace:
using System.Linq;
Create a string array of selected items and then use string.join:
var selection = listbox_software.SelectedItems
.Cast<string>()
.ToArray();
var str = string.Join(",", selection);
I found out the answer.
// To access checkbox list item's value //
string total = "";
foreach (ListItem listItem in listbox_software.Items)
{
if (listItem.Selected)
{
total = total + "[" + listItem.Value + "][ " + " ";
}
}
string str = total.ToString();

Writing data to SQL and dumping it into Excel

My C# application is significantly slower than I would like. The program accesses an Excel sheet and loops through each row on a sheet / does the following:
Collects variables from that row
Creates an SQL query based off those variables
Executes that query
then a reader goes out and puts it in its proper column on that same row.
*Note, each row has 6 different SQL queries/ final numbers that are calculated and input into the sheet, the code below is just showing the first 2 for brevity's sake. The sheet has around 300 rows, so the program is executing 300 * 6= 1,800 SQL queries each time its run. For each one of those 1,800 numbers, the program is accessing the sheet and inputting it into the sheet.
Instead of doing the excelWorksheet.get_Range and inputting the number into the Excel sheet for each number, one at a time, would it be faster to store each number into an array and then go back later and mass dump all of the numbers into the sheet, once all of the queries have been executed and the array is full?
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data Source=WRDXPVSEPIRPT00;DATABASE=Epicor905;Workstation ID=SMEBPPL204TN;Trusted_Connection=true";
try
{
//initiate the connection
conn.Open();
}
catch(SqlException ex)
{
throw new ApplicationException(string.Format("You're not connected to the database, please close the program, re-connect to the network, and try again."), ex);
}
progressBar1.Value = 60;
statusLabel.Text = "Retrieving account balances from database...";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//iterate through each row and pull information
for (int i = 2; i < lastUsedRow + 1; i++)
{
//string iString = Convert.ToString(i);
statusLabel.Text = "Retrieving balances for " + i + " of " + lastUsedRow + " accounts...";
//declare excel sheet range variables
var CompanyVar = excelWorksheet.get_Range("A" + i, "A" + i).Text;
var FiscalYear = excelWorksheet.get_Range("B" + i, "B" + i).Text;
var FiscalPeriod = excelWorksheet.get_Range("C" + i, "C" + i).Text;
var segValue1 = excelWorksheet.get_Range("F" + i, "F" + i).Text;
var segValue2 = excelWorksheet.get_Range("G" + i, "G" + i).Text;
var segValue3 = excelWorksheet.get_Range("H" + i, "H" + i).Text;
int FiscalYearHelper = Convert.ToInt32(FiscalYear);
var FiscalYearPYY = FiscalYearHelper - 1;
//begin filling in CY YTD column
string SQLCode = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
" FiscalPeriod between 1 AND " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
"AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
"AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";
SqlCommand command = new SqlCommand(SQLCode, conn);
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string cyAct = reader["BalanceAmt"].ToString();
if (cyAct == "")
{
goto CYM;
//cyAct = "0.00";
}
var cyAct1 = (float)Convert.ToDouble(cyAct);
int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
double cyAct2 = (cyAct1 * one);
string cyAct3 = cyAct2.ToString("0.##");
excelWorksheet.get_Range("I" + i, "I" + i).Value = cyAct3;
}
}
//end filling in column
//begin filling in CY Month column
CYM:
string SQLCodeMonth = "SELECT SUM(DebitAmount-CreditAmount) as BalanceAmt FROM GLJrnDtl WITH (NOLOCK) WHERE" +
" FiscalPeriod = " + FiscalPeriod + "AND Company =" + "'" + CompanyVar + "'" +
"AND FiscalYear =" + "'" + FiscalYear + "'" + "AND SegValue1 LIKE " + "'" + segValue1 + "'" +
"AND SegValue2 LIKE " + "'" + segValue2 + "'" + "AND SegValue3 LIKE " + "'" + segValue3 + "'";
SqlCommand commandMonth = new SqlCommand(SQLCodeMonth, conn);
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = commandMonth.ExecuteReader())
{
while (reader.Read())
{
string cyAct = reader["BalanceAmt"].ToString();
if (cyAct == "")
{
goto APY;
//cyAct = "0.00";
}
var cyAct1 = (float)Convert.ToDouble(cyAct);
int one = Convert.ToInt32(excelWorksheet.get_Range("E" + i, "E" + i).Text);
double cyAct2 = (cyAct1 * one);
string cyAct3 = cyAct2.ToString("0.##");
excelWorksheet.get_Range("J" + i, "J" + i).Value = cyAct3;
}
}
//end filling in column
//begin filling in Act PY month column
THIS IS NOT A FULL ANSWER, there is not enough space to write this as a comment, do not mark this as an answer its a comment.
Please try to use objects (instances of classes or structs) it will make your programming more efficient and easy to maintain.
for example:
private void UseObjects()
{
List<ExcelObjects> ListOfvarsForQuery = new List<ExcelObjects>();
for (int i = 2; i < lastUsedRow + 1; i++)
{
ExcelObjects obj = new ExcelObjects();
obj.CompanyVar = ws.Cells[i, 1];
obj.FiscalYear = ws.Cells[i, 2];
obj.FiscalPeriod = ws.Cells[i, 3];
obj.segValue1 = ws.Cells[i, 4];
obj.segValue2 = ws.Cells[i, 5];
obj.segValue3 = ws.Cells[i, 6];
ListOfvarsForQuery.Add(obj);
}
string SQLCode = // use the list of ExcelObjects and write a better query.
}
}
struct ExcelObjects
{
public string CompanyVar;
public string FiscalYear;
public string FiscalPeriod;
public string segValue1;
public string segValue2;
public string segValue3;
}
Instead of looping through each row and running a SQL query for each row, I found that it is faster to outer join the table I speak of in my question with another SQL table that has the account balances on it. I'm doing all of it within memory because I've been coding for 3 weeks and I don't have time to learn how to create a temp table in SQL server yet.

Concatenate strings with += operator

I am really new to ASP.NET, C#.
Now I am trying to write a little method, what is build me an sql query.
(Later I will use prepared statements, now I am just try to get acquainted with the environment, with the language, etc...)
Here is my method:
public void insert( string table, Dictionary<string, string> dataToInsert ) {
string sql = "INSERT INTO " + table;
if (dataToInsert.Count< 1) {
throw new Exception("No data to insert to table: " + table);
}
List<string> fieldNames = getFieldNames(dataToInsert);
List<string> aposthrofedFieldNames = getApostrophedValues(fieldNames);
List<string> values = getValues(dataToInsert);
List<string> aposthrofedValues = getApostrophedValues(values);
string fieldNamesString = string.Join(", ", aposthrofedFieldNames);
string valuesString = string.Join(", ", aposthrofedValues);
sql += " (" + fieldNamesString + ") VALUES (" + valuesString + ")";
}
The fieldNamesString and valuesString are just concatenated strings like `'userId', 'loginDate', ... so nothing special, just strings.
At this line:
sql += " (" + fieldNamesString + ") VALUES (" + valuesString + ")";
the sql variable has gone. Can not be watchable, no more datatip.
What do I do wrong?
EDIT
Screenshot:
UPDATE
If I am using this, sql will be ok:
sql = string.Concat(sql, " (", fieldNamesString, ") VALUES (", valuesString, ")");

Multiple OleDbCommands producing System Resource Exceeded

So basically I have a C# project, that iterates through every student (300 students) within a table called Student within a Microsoft Access 2016 database. In a single iteration for a single student by using other tables like Mathematics, Reading that have a 1-to-1 relationship with the Student table, to grab the data that belongs to that student.
try
{
OleDbCommand allStudents = new OleDbCommand("SELECT [NSN]"
+ " FROM [Student]; ");
allStudents.Connection = conn;
OleDbDataAdapter allData = new OleDbDataAdapter(allStudents);
DataTable allTable = new DataTable();
allData.Fill(allTable);
foreach (DataRow dr in allTable.Rows)
{
string NSN = dr["NSN"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * "
+ "FROM (((([Student] s "
+ "INNER JOIN [Student Extra] se ON se.[NSN] = s.[NSN]) "
+ "INNER JOIN [Reading] r ON r.[NSN] = s.[NSN])"
+ "INNER JOIN [Writing] w ON w.[NSN] = s.[NSN])"
+ "INNER JOIN [Mathematics] m ON m.[NSN] = s.[NSN]) "
+ "WHERE s.[NSN] = '" + NSN + "'; ");
cmd.Connection = conn;
OleDbDataAdapter daa = new OleDbDataAdapter(cmd);
DataTable dtt = new DataTable();
daa.Fill(dtt);
foreach (DataRow drr in dtt.Rows)
{
firstName = drr["Preferred Name"].ToString();
gender = drr["Gender"].ToString();
room = drr["Room Number"].ToString();
NSAchieve = drr["National Standard Achieve"].ToString();
NSProgress = drr["National Standard Progress"].ToString();
The above code is only a snippet of the code I have, but this is basically where the function will start.
By using this data, I want to be able to go through several SELECT statements for other tables and compare them and produce a calculated value.
Dictionary<string, OleDbCommand> d = new Dictionary<string, OleDbCommand>();
cmd = new OleDbCommand("SELECT [Achievement Statement]"
+ " FROM [National Standard Codes]"
+ " WHERE [National Standard Code] = '" + readingNSAchievementCode + "'; ");
d["readingNSAchievementOTJ"] = cmd;
cmd = new OleDbCommand("SELECT [" + NSAchieve + "]"
+ " FROM [Reading National Standards]"
+ " WHERE [Assessment] = '" + readingFinalAssessment + "'; ");
d["readingNSAchievementComp"] = cmd;
cmd = new OleDbCommand("SELECT [Timeframe]"
+ " FROM [Reading Statements]"
+ " WHERE [Year Code] = '" + NSProgress + "'; ");
d["readingNSProgressTimeframe"] = cmd;
There are several more commands, (approx <150). I use a Dictionary to store my Commands, and then execute the commands in a FOREACH loop.
foreach(KeyValuePair<string, OleDbCommand> pair in d)
{
try
{
string v = pair.Key;
OleDbCommand dbCmd = pair.Value;
dbCmd.Connection = conn;
OleDbDataReader reader = dbCmd.ExecuteReader();
reader.Read();
readingDict[v] = reader.GetString(0);
}
catch (Exception e)
{
MessageBox.Show("Error at " + pair.Key + "\n\n Here is message " + e);
}
}
After executing and getting my value, I want to store my data into another table called Calculated.
string insert1 = "INSERT INTO [Calculated] (";
int i = 0;
Dictionary<string, string> dict = createDictionary(NSN);
int len = dict.Count / 2;
foreach (KeyValuePair<string, string> pair in dict)
{
string field = pair.Key;
string value = pair.Value;
if (i == (len - 1))
{
insert1 += "[" + field + "])";
break;
}
else
{
insert1 += "[" + field + "], ";
}
i++;
}
insert1 += " VALUES (";
i = 0;
foreach (KeyValuePair<string, string> pair in dict)
{
string field = pair.Key;
string value = pair.Value;
if (i == len - 1)
{
insert1 += "'" + value + "')";
break;
}
else
{
insert1 += "'" + value + "', ";
}
i++;
}
I build my INSERT INTO query, and then I execute using an OleDbCommand. This needs to repeat 300 times, but for development purposes currently I only have 5 students in my Student table. However when executing after the 4th student it will always consistently give me an error System Resources Exceeded always at a specific OleDbCommand. I have tested each command separately, so there is no issue with the way the OleDbCommands are written.
I have tried searching on here, and tried to encase the first code snippet in a using statement, using using (OleDbConnection conn = new OleDbConnection(connectionStr)) but as I am still a novice at C#, I am unable to produce a solution.

Issues with the update query SQL

am writing a c# code in which am trying to update 4 of the 10 columns of the table. Here is my function type in which am sending arguments for the query:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
Now what happens is that i call this function somewhere in my program providing values in argument:
checkout_visitor(chk_in,chk_out,t_out,dt_out,idcardnum);
The query am using to update my columns is given by:
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = "+ v_idd;
Given me exception incorrect syntax near chkout. Where am i wrong?? is the syntax correct? how do i correct it?
code:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
{
try
{
connection.Open();
String query = "select v_id from visitor where visitor.cnic=" + cnic;
command = connection.CreateCommand();
command.CommandText = query;
visitor_id = command.ExecuteScalar().ToString();
int v_idd = Int32.Parse(visitor_id);
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = " + v_idd;
//String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = " + time_out + ",[date_out] =" + date_out + " where visit_detail.v_id = " + v_idd;
command = connection.CreateCommand();
command.CommandText = query2;
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
catch (Exception e)
{
return -1;
}
}
Problem :
1.you are not seperating the Parameters properly using comma , .
2.you are not giving the sapace between SET and check_in parameter.
Try This:
String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = '" + time_out + "',[date_out] ='" + date_out + "' where visit_detail.v_id = "+ v_idd;
Do you see the resulting query? It seems to me you're missing some comma, but you should print (and post) the resulting query to have a better understanding of the issue.
You are missing ',' between the column names.
Its like Update Table Set col1=3,col2='test'
The problem is that query2 string will be something along the lines:
UPDATE visit_detail SET[check_in] = " 1[check_out] = 2[time_out] = some time[date_out] =some datewhere visit_detail.v_id = 5
So you can already see that there's datewhere that is incorect, there are also no ' characters around string parameters, and no commas between parameters.
Quick fix to that would be:
String query2 = String.Format("UPDATE visit_detail SET [check_in]={0}, [check_out]={1}, [time_out]='{2}', [date_out]='{3}' where visit_detail.v_id={4};", check_inn, checkout, time_out, date_out, v_idd);
But this is still not valid. If time_out contains ' characters, you'll again receive an error.
What you should really use is this:
SqlCommand.Parameters
This is a proper way of passing paramters to your command, all the problems will be taken care of for you.

Categories

Resources