UPDATE query on Access Database not working C#.NET - c#

I am working on a database management system. I have a simple task of updating user profile. I created an asp.net page with textboxes and a save button. After adding the text I click on the save button. The code for the button is
protected void Button1_Click(object sender, EventArgs e)
{
string firstName = TextBox2.Text;
string lastName = TextBox1.Text;
string sCourse = TextBox3.Text;
string sTelephone = TextBox4.Text;
string sAddress = TextBox5.Text;
string sEmail = TextBox6.Text;
string Gender = TextBox7.Text;
string user = User.Identity.Name;
OleDbConnection oleDBConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\ASPNetDB.accdb");
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Email", sEmail);
oleDBConn.Open();
cmd.ExecuteNonQuery();
}
But nothing happens. The database is not updated. Is the code correct?

Add the parameter values in the same order as the parameter names appear in the UPDATE statement.
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);
OleDb with Access does not pay attention to the parameter names, only their order.

add the parameters according to the order in the query
string sqlQuerry = "UPDATE aspnet_Users SET firstName=#firstName, lastName=#lastName, Gender=#Gender, Address=#Address, Telephone=#Telephone, Course=#Course, Email=#email WHERE UserName=#UserName";
OleDbCommand cmd = new OleDbCommand(sqlQuerry, oleDBConn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#firstName", firstName);
cmd.Parameters.AddWithValue("#lastName", lastName);
cmd.Parameters.AddWithValue("#Gender", Gender);
cmd.Parameters.AddWithValue("#Address", sAddress);
cmd.Parameters.AddWithValue("#Telephone", sTelephone);
cmd.Parameters.AddWithValue("#Course", sCourse);
cmd.Parameters.AddWithValue("#Email", sEmail);
cmd.Parameters.AddWithValue("#UserName", User.Identity.Name);

Related

How to post records from my windows form to my database

Good day, thanks for the assistance previously. please am trying to POST records from my window form to database, am having challenges with it, how do i do it?
Below is the code snippet i coded it with
private void btnNext_Click(object sender, EventArgs e)
{
//Calling Window Work experience page
WorkExperience frm = new WorkExperience();
frm.ShowDialog();
string connectionString = #"Data Source=localhost;" +
"Initial Catalog=EmploymentDb;Integrated Security=true; User Instance=False";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
//command.CommandText
string sql = "INSERT INTO EmploymentDb " +
"(Id,Title, LastName, FirstName, MiddleName, Gender, Address, Email, City, State, MobileNumber, DateOfBirth, HomePhone, DistchargeCertNumber, SchoolAttended, NYSCStatus, AgeLimit) VALUES " +
"(#Id, #Title, #LastName, #FirstName, #MiddleName, #Gender, #Address, #Email, #City, #State, #MobileNumber, #DateOfBirth, #HomePhone, #DistchargeCertNumber, #SchoolAttended, #NYSCStatus, #AgeLimit)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Id", txtID.Text);
cmd.Parameters.AddWithValue("#Title", comboBoxtTitle.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMiddleName.Text);
cmd.Parameters.AddWithValue("#Gender", comboBoxGender.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#City", comboBoxCity.Text);
cmd.Parameters.AddWithValue("#State", comboBoxState.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNo.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", dateTimePickerDOB.Text);
cmd.Parameters.AddWithValue("#HomePhone", txtHomePhone.Text);
cmd.Parameters.AddWithValue("#DistchargeCertNumber", txtNYSCCertNumder.Text);
cmd.Parameters.AddWithValue("#SchoolAttended", txtSchoolAttended.Text);
cmd.Parameters.AddWithValue("#NYSCStatus", comboBoxNYSCStatus.Text);
cmd.Parameters.AddWithValue("#AgeLimit", cbxAgeLimit.Text);
int affectedRows = cmd.ExecuteNonQuery();
MessageBox.Show(affectedRows + "Row inserted!");
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "Employment");
FillControls();
btnNext.Enabled = true;
// btnPrevious.Enabled = true;
}
You need to provide SqlConnection for SqlDataAdapter, if you want to retrieve the data back. Otherwise, you can delete the following 4 lines of code.
var query = "SELECT Id,Title FROM EmploymentDb";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
^^^^^^
DataSet ds = new DataSet();
da.Fill(ds, "Employment");

Must declare the scalar variable "#Emp_ID"

con.Open();
//stringquery=("insert into Tbl_EmployeeDetails values='"+txtName.Text+"','"+txtContact.Text+"','"+txtAddress.Text+"','"+txtEmployeeID.Text+"','"+txtJobLocation.Text+"','"+txtDateOfBirth.Text+"','"+Rdllist.selectedItem.Text+"'");
//sql command cmd=new sqlcommand(query,con);
//cmd.ExecuteNonquery();
SqlCommand cmd= new SqlCommand("Insert into Tbl_EmployeeDetails(Name,Address,Contact,Emp_ID,JobLocation,DateOfBirth,Gender)values(#Name,#Address,#Contact,#Emp_ID,#JobLocation,#DateOfBirth,#Gender)",con);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Contact", txtContact.Text);
cmd.Parameters.AddWithValue("#Employee_ID", txtEmp_ID.Text);
cmd.Parameters.AddWithValue("#JobLocation", txtJobLocation.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", txtDateOfBirth.Text);
cmd.Parameters.AddWithValue("#Gender", Rdllist.SelectedItem.Text);
cmd.ExecuteNonQuery();
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),"alertMessage","alert('Record Inserted Successfully')",true);
txtName.Text= String.Empty;
txtAddress.Text= String.Empty;
txtContact.Text= String.Empty;
txtEmp_ID.Text= String.Empty;
txtJobLocation.Text= String.Empty;
txtDateOfBirth.Text= String.Empty;
// txtGender.Text= String.Empty;
con.Close();
}
}
#Employee_ID should be #Emp_ID the same as it is with your query.
eg:
cmd.Parameters.AddWithValue("#Emp_ID", txtEmp_ID.Text);
Hence try this:
con.Open();
SqlCommand cmd= new SqlCommand("Insert into Tbl_EmployeeDetails(Name,Address,Contact,Emp_ID,JobLocation,DateOfBirth,Gender)values(#Name,#Address,#Contact,#Emp_ID,#JobLocation,#DateOfBirth,#Gender)",con);
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Contact", txtContact.Text);
cmd.Parameters.AddWithValue("#Emp_ID", txtEmp_ID.Text);
cmd.Parameters.AddWithValue("#JobLocation", txtJobLocation.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", txtDateOfBirth.Text);
cmd.Parameters.AddWithValue("#Gender", Rdllist.SelectedItem.Text);
cmd.ExecuteNonQuery();
ScriptManager.RegisterClientScriptBlock(this,this.GetType(),"alertMessage","alert('Record Inserted Successfully')",true);
txtName.Text= String.Empty;
txtAddress.Text= String.Empty;
txtContact.Text= String.Empty;
txtEmp_ID.Text= String.Empty;
txtJobLocation.Text= String.Empty;
txtDateOfBirth.Text= String.Empty;
// txtGender.Text= String.Empty;
con.Close();
}
}
Or you can just change your values to:
values(#Name,#Address,#Contact,#Employee_ID,#JobLocation,#DateOfBirth,#Gender)
Since you called it like this:
cmd.Parameters.AddWithValue("#Employee_ID", txtEmp_ID.Text);
or
values(#Name,#Address,#Contact,#Emp_ID,#JobLocation,#DateOfBirth,#Gender)
cmd.Parameters.AddWithValue("#Emp_ID", txtEmp_ID.Text);
Whatever the name in values is going to be used in cmd.parameters.addwithvalue.
Beware of the pitfalls of AddWithValue: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Error converting data type varchar to numeric. I used varchar data type and trying to insert 18-24 value

I have table
name |datatype
uid |int
name |varchar(50)
email |varchar(32)
pass |varchar(32)
about |varchar(100)
age |varchar(20)
gender |varchar(50)
address |varchar(100)
phno |numeric(18, 0)
style |varchar(30)
I give varchar data type to age field and trying to insert 18-24 value, so it's showing me error like this --
"Error converting data type varchar to numeric."
cnn.Open();
cmd = new SqlCommand("update tblregister set name='"+txtname .Text +"', pass='"+txtpass .Text +"',about='"+txtabout .Text +"', age='"+drpage.SelectedItem.Text +"', gender='"+rd .SelectedValue +"', address='"+txtadd .Text +"', phno='"+txtphno.Text +"' where email='"+Session ["user"]+"' ", cnn);
cmd.ExecuteNonQuery();
cnn.Close();
what should I do?
Your table column phno is numeric and you are saving data as varchar..
Also always use parameterised query to avoid SQL Injection
try below code
cnn.Open();
cmd = new SqlCommand(#"update tblregister set name=#name,pass=#pass,about=#about,
age=#age,gender=#gender,address=#address,phno=#phonenum where email = #email",cnn);
cmd.Parameters.AddWithValue("#name", txtname .Text);
cmd.Parameters.AddWithValue("#pass", txtpass .Text);
cmd.Parameters.AddWithValue("#about", txtabout .Text);
cmd.Parameters.AddWithValue("#age", drpage.SelectedItem.Text);
cmd.Parameters.AddWithValue("#gender", rd .SelectedValue);
cmd.Parameters.AddWithValue("#address", txtadd .Text );
cmd.Parameters.AddWithValue("#phonenum",Convert.ToInt64(txtphno.Text));
cmd.Parameters.AddWithValue("#email", Session ["user"].ToString());
cmd.ExecuteNonQuery();
cnn.Close();
Little bit modification on Sachu's Answer
cnn.Open();
cmd = new SqlCommand(#"update tblregister set name=#name,pass=#pass,about=#about,
age=#age,gender=#gender,address=#address,phno=#phonenum where email = #email",cnn);
cmd.Parameters.AddWithValue("#name", txtname .Text);
cmd.Parameters.AddWithValue("#pass", txtpass .Text);
cmd.Parameters.AddWithValue("#about", txtabout .Text);
cmd.Parameters.AddWithValue("#age", drpage.SelectedItem.Text);
cmd.Parameters.AddWithValue("#gender", rd .SelectedValue);
cmd.Parameters.AddWithValue("#address", txtadd .Text );
cmd.Parameters.AddWithValue("#phonenum",Convert.ToInt64(txtphno.Text.Trim()));
cmd.Parameters.AddWithValue("#email", Session ["user"].ToString());
cmd.ExecuteNonQuery();
cnn.Close();
Try This:
cnn.Open();
cmd = new SqlCommand(#"update tblregister set name=#name,pass=#pass,about=#about,
age=#age,gender=#gender,address=#address,phno=#phno where email = #email",cnn);
cmd.Parameters.AddWithValue("#name", txtname .Text);
cmd.Parameters.AddWithValue("#pass", txtpass .Text);
cmd.Parameters.AddWithValue("#about", txtabout .Text);
cmd.Parameters.AddWithValue("#age", drpage.SelectedItem.Text);
cmd.Parameters.AddWithValue("#gender", rd .SelectedValue);
cmd.Parameters.AddWithValue("#address", txtadd .Text );
cmd.Parameters.AddWithValue("#phno",Convert.ToInt64(txtphno.Text.Trim()));
cmd.Parameters.AddWithValue("#email", Session ["user"].ToString());
cmd.ExecuteNonQuery();
cnn.Close();

How do I go about adding records into TWO tables into Access Database?

I am a new member. Also, I am trying to add a record into 2 different tables (customerinfo & studentinfo). My code is below but it only records the textbox fields into the StudentInfo Table only. How should I go about it putting the record into 2 tables simultaneously?
Thanks
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
Type csType = this.GetType();
//check to ensure that UserId keyed in is not being used by other Customers
OleDbCommand cmd;
OleDbCommand cmd1;
OleDbDataReader rdr;
OleDbDataReader rdr1;
string strSQLSelect = "SELECT sUserId FROM studentInfo ORDER BY sUserId";
string strSQLSelect1 = "SELECT cUserId FROM customerInfo ORDER BY cUserId";
cmd1 = new OleDbCommand(strSQLSelect1, mDB);
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
rdr1 = cmd1.ExecuteReader();
this.txtPassword.Attributes.Add("value", this.txtPassword.Text);
// insert new record
string strSQLInsert = "INSERT INTO "
+ "studentInfo (sUserId,sPassword,sName,sAddress,sTel,sEmail,sLevel, sLevel2)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#lvl,#lvl2)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#tel", txtTel.Text);
cmd.Parameters.AddWithValue("#lvl", DropDownList1.Text);
cmd.Parameters.AddWithValue("#lvl2", DropDownList2.Text);
string strSQLInsert1 = "INSERT INTO "
+ "customerInfo (cUserId,cPassword,cName,cAddress,cEmail,cTel,cCountry)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#country)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd1 = new OleDbCommand(strSQLInsert1, mDB);
cmd1.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd1.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd1.Parameters.AddWithValue("#name", txtName.Text);
cmd1.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd1.Parameters.AddWithValue("#em", txtEmail.Text);
cmd1.Parameters.AddWithValue("#tel", txtTel.Text);
cmd1.Parameters.AddWithValue("#country", txtCountry.Text);
cmd.ExecuteNonQuery();
mDB.Close();
It looks like you're missing
cmd1.ExecuteNonQuery()
for the other table.

SQL Insert in While Loop

I am trying to use a while loop to loop through some data and then add each one to sql. This is the code I've done so far:
SqlCommand cmd = new SqlCommand();
cmd.Connection = SqlConn;
while (dr.Read())
{
cmd.CommandText = "insert into CPC_Coupons(PortalID, CreatedByUser, CouponCode, ProductID, ExpiresOn, Quantity, Title, FirstName, LastName, Company, Address1, City, Region, Zip, Country, WorkPhone, Email, Campaign, Source, Market, Notes) values(#PortalID, #CreatedByUser, #Coupon, #ProductID, #ExpiresOn, #Quantity, #Title, #FirstName, #LastName, #Company, #Address1, #City, #Region, #Zip, #Country, #WorkPhone, #Email, #Campaign, #Source, #Market, #Notes)";
cmd.Parameters.Add("#PortalID", SqlDbType.NVarChar).Value = 0;
cmd.Parameters.Add("#Coupon", SqlDbType.NVarChar).Value = dr[0].ToString();
cmd.Parameters.Add("#CreatedByUser", SqlDbType.NVarChar).Value = "3517";
cmd.Parameters.Add("#ProductID", SqlDbType.NVarChar).Value = "0";
cmd.Parameters.Add("#ExpiresOn", SqlDbType.NVarChar).Value = "01/01/2013";
cmd.Parameters.Add("#Quantity", SqlDbType.NVarChar).Value = "100";
cmd.Parameters.Add("#Title", SqlDbType.NVarChar).Value = "Mr.";
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = dr[3].ToString();
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = dr[4].ToString();
cmd.Parameters.Add("#Company", SqlDbType.NVarChar).Value = dr[2].ToString();
cmd.Parameters.Add("#Address1", SqlDbType.NVarChar).Value = dr[5].ToString();
cmd.Parameters.Add("#City", SqlDbType.NVarChar).Value = dr[6].ToString();
cmd.Parameters.Add("#Region", SqlDbType.NVarChar).Value = dr[7].ToString();
cmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = dr[8].ToString();
cmd.Parameters.Add("#Country", SqlDbType.NVarChar).Value = dr[9].ToString();
cmd.Parameters.Add("#WorkPhone", SqlDbType.NVarChar).Value = dr[10].ToString();
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = dr[11].ToString();
cmd.Parameters.Add("#Campaign", SqlDbType.NVarChar).Value = txtCampaign.Text;
cmd.Parameters.Add("#Source", SqlDbType.NVarChar).Value = dr[12].ToString();
cmd.Parameters.Add("#Market", SqlDbType.NVarChar).Value = txtMarketSegment.Text;
cmd.Parameters.Add("#Notes", SqlDbType.NVarChar).Value = txtNotesToSales.Text;
cmd.CommandType = CommandType.Text;
SqlConn.Open();
cmd.ExecuteNonQuery();
SqlConn.Close();
}
But one the second pass through it gets to the cmd.ExecuteNonQuery(); and gives this error: The variable name '#PortalID' has already been declared. Variable names must be unique within a query batch or stored procedure.
Any idea what I am doing wrong?
Thanks!
Instantiating a new SQLCommand inside the loop would probably fix your issue. Like so:
while (dr.Read())
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = SqlConn;
cmd.CommandText = "insert into CPC_Coupons(PortalID, CreatedByUser, CouponCode, ProductID, ExpiresOn, Quantity, Title, FirstName, LastName, Company, Address1, City, Region, Zip, Country, WorkPhone, Email, Campaign, Source, Market, Notes) values(#PortalID, #CreatedByUser, #Coupon, #ProductID, #ExpiresOn, #Quantity, #Title, #FirstName, #LastName, #Company, #Address1, #City, #Region, #Zip, #Country, #WorkPhone, #Email, #Campaign, #Source, #Market, #Notes)";
cmd.Parameters.Add("#PortalID", SqlDbType.NVarChar).Value = 0;
cmd.Parameters.Add("#Coupon", SqlDbType.NVarChar).Value = dr[0].ToString();
cmd.Parameters.Add("#CreatedByUser", SqlDbType.NVarChar).Value = "3517";
cmd.Parameters.Add("#ProductID", SqlDbType.NVarChar).Value = "0";
cmd.Parameters.Add("#ExpiresOn", SqlDbType.NVarChar).Value = "01/01/2013";
cmd.Parameters.Add("#Quantity", SqlDbType.NVarChar).Value = "100";
cmd.Parameters.Add("#Title", SqlDbType.NVarChar).Value = "Mr.";
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = dr[3].ToString();
cmd.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = dr[4].ToString();
cmd.Parameters.Add("#Company", SqlDbType.NVarChar).Value = dr[2].ToString();
cmd.Parameters.Add("#Address1", SqlDbType.NVarChar).Value = dr[5].ToString();
cmd.Parameters.Add("#City", SqlDbType.NVarChar).Value = dr[6].ToString();
cmd.Parameters.Add("#Region", SqlDbType.NVarChar).Value = dr[7].ToString();
cmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = dr[8].ToString();
cmd.Parameters.Add("#Country", SqlDbType.NVarChar).Value = dr[9].ToString();
cmd.Parameters.Add("#WorkPhone", SqlDbType.NVarChar).Value = dr[10].ToString();
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = dr[11].ToString();
cmd.Parameters.Add("#Campaign", SqlDbType.NVarChar).Value = txtCampaign.Text;
cmd.Parameters.Add("#Source", SqlDbType.NVarChar).Value = dr[12].ToString();
cmd.Parameters.Add("#Market", SqlDbType.NVarChar).Value = txtMarketSegment.Text;
cmd.Parameters.Add("#Notes", SqlDbType.NVarChar).Value = txtNotesToSales.Text;
cmd.CommandType = CommandType.Text;
SqlConn.Open();
cmd.ExecuteNonQuery();
SqlConn.Close();
}
But, are you sure you want to do this. Why not insert all your data in one go? -For instance see Yucks answers.
You should create these parameters outside the loop with default values and, during each iteration, access to them and set its new parameters arguments.
Summary: don't add them for each iteration, access them!
EDIT:
In order to be more concrete, check this MSDN entry:
SqlParameterCollection indexer http://msdn.microsoft.com/en-us/library/dk96b781.aspx
cmd has a scope outside your while loops, so everything you set (i.e. the parameters) persists between iterations.
Change it to this so it will work:
while (dr.Read())
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = SqlConn;
// ... rest as before
}
You'd be better off filling a DataSet and then looping through that, or accumulating its results to be sent once to a stored procedure. For any large result sets this is going to be very inefficient.
As you are reusing the command object, you will be adding another set of parameters on the second iteration.
Add the parameters outside the loop, and set the values that changes inside the loop.
Also, you should open the database connection before the loop and close it after.
You don't need to open and close the connection every time.
You don't need to create a new SqlCommand every time.
SqlCommand cmd = new SqlCommand();
cmd.Connection = SqlConn;
cmd.CommandText = "insert into CPC_Coupons(PortalID, CreatedByUser, CouponCode, ProductID, ExpiresOn, Quantity, Title, FirstName, LastName, Company, Address1, City, Region, Zip, Country, WorkPhone, Email, Campaign, Source, Market, Notes) values(#PortalID, #CreatedByUser, #Coupon, #ProductID, #ExpiresOn, #Quantity, #Title, #FirstName, #LastName, #Company, #Address1, #City, #Region, #Zip, #Country, #WorkPhone, #Email, #Campaign, #Source, #Market, #Notes)";
cmd.CommandType = CommandType.Text;
SqlConn.Open();
while (dr.Read())
{
cmd.Parameters.Clear()
cmd.Parameters.Add("#PortalID", SqlDbType.NVarChar).Value = 0;
''' other parameters here
cmd.ExecuteNonQuery();
}
SqlConn.Close();

Categories