SQL Insert in While Loop - c#

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();

Related

System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value to data type int.'

I have creates a database and I am trying to INSERT INTO TABLE with the following code:
string sqlquery = "INSERT INTO Runner VALUES (#firstName, #lastName, #amount, #category, #city, #charity, #route)";
cmd = new SqlCommand(sqlquery, conn);
conn.Open();
cmd.Parameters.AddWithValue("#firstName", txtFirstName.Text.ToString());
cmd.Parameters.AddWithValue("#lastName", txtLastName.Text.ToString());
cmd.Parameters.AddWithValue("#amount", Convert.ToInt32(txtMoney.Text));
cmd.Parameters.AddWithValue("#category", cbBoxCategory.ValueMember);
cmd.Parameters.AddWithValue("#city", cbBoxCity.ValueMember);
cmd.Parameters.AddWithValue("#charity", cbBoxCharity.ValueMember);
cmd.Parameters.AddWithValue("#route", cbBoxRoute.ValueMember);
cmd.ExecuteNonQuery();
conn.Close();
When I run it, I get this error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'id' to data type int.'
All my cbBox (comboBox) need to leave a INT, I understand that is need to convert to NVARCHAR to INT, I try to use Convert.Into32(cbBox.Category.ValueMember) but without success.
I have tried everything with no success.
After looking for other people answer I find this solution.
string sqlquery = "INSERT INTO Runner (firstName, lastName, amount, categoryID, cityID, charityID, routeID) VALUES (#firstName, #lastName, #amount, #category, #city, #charity, #route)";
cmd = new SqlCommand(sqlquery, conn);
conn.Open();
cmd.Parameters.Add("#firstName", SqlDbType.VarChar, 50).Value = txtFirstName.Text;
cmd.Parameters.Add("#lastName", SqlDbType.VarChar, 50).Value = txtLastName.Text;
cmd.Parameters.Add("#amount", SqlDbType.Int).Value = txtMoney.Text;
cmd.Parameters.Add("#category", SqlDbType.Int).Value = cbBoxCategory.SelectedValue;
cmd.Parameters.Add("#city", SqlDbType.Int).Value = cbBoxCity.SelectedValue;
cmd.Parameters.Add("#charity", SqlDbType.Int).Value = cbBoxCharity.SelectedValue;
cmd.Parameters.Add("#route", SqlDbType.Int).Value = cbBoxRoute.SelectedValue;
cmd.ExecuteNonQuery();
MessageBox.Show("New Runner has been registered!");
conn.Close();
By using Convert.ToInt32(cbBoxRoute.SelectedValue)
Here is the link where I find my solution:
Insert ID into SQL from C# Combo box

Is this a proper way of putting quotes in SQL query in ADO.NET

string query = #"INSERT INTO Uczniowie (ID, Name, Surname, Age)" +
"VALUES('" + textBox1.Text + "'" +
", '" + textBox2.Text + "'" +
",'" + textBox3.Text + "'" +
",'" + textBox3.Text + "'";
NO, it's not since it's now open to SQL Injection attack. Rather use a parameterized query like
string query = "INSERT INTO Uczniowie (ID, Name, Surname, Age) VALUES(#id, #name, #surname, #age)";
See MSDN documentation on How to: Execute a Parameterized Query for more information on the same
You should use parameters instead: SqlCommand.Parameter
Could look like this
string commandText = "INSERT INTO Uczniowie (ID, Name, Surname, Age)" +
"VALUES(#id, #name, #surname, #age)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#id", SqlDbType.Int);
command.Parameters["#id"].Value = textBox1.Text;
...
}
This will avoid SQL Injection, as well.
This is the old syntax. You can try like this :
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (#FirstName, #Lastname, #Username, #Password, #Age, #Gender, #Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("#Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("#Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("#Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
No. You can simply do this. like
string query = #"INSERT INTO Uczniowie (ID, Name, Surname, Age) VALUES(#id, #name, #surname, #age)";
And than add Parameters using sqlCmd like-
sqlcmd.Parameter.Add[#id].Values=textbox1.text;

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");

Failed to convert parameter value from a DataRowView to a Int32

I'm inserting records and one of my object is combobox. The combox is connected to the table. When i'm inserting this error appear:
Failed to convert parameter value from a DataRowView to a Int32
My code:
cn.Open();
SqlCommand Insert = new SqlCommand();
Insert.Connection = cn;
Insert.CommandType = CommandType.Text;
Insert.CommandText = "INSERT INTO Ticket VALUES (CustomerID, Date, Store, Amount, NoStub) ";
Insert.Parameters.Add("CustomerID", SqlDbType.Int).Value = cboName.SelectedValue;
Insert.Parameters.Add("Date", SqlDbType.DateTime).Value = dtpDate.Value.Date.ToString();
Insert.Parameters.Add("Store", SqlDbType.NVarChar).Value = txtStore.Text;
Insert.Parameters.Add("Amount", SqlDbType.Decimal).Value = txtAmount.Text;
Insert.Parameters.Add("NoStub", SqlDbType.Decimal).Value = txtStub.Text;
Insert.ExecuteNonQuery();
cn.Close();
Use this sample code:
command.Parameters.Add("#CustomerID", SqlDbType.Int).Value = Convert.ToInt32(storeCode);
or use
int.parse for cboName.
Change your code to the following and let the Server resolve the data type
cn.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = cn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)
VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
sqlCmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
sqlCmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
sqlCmd.Parameters.AddWithValue("#Store", txtStore.Text);
sqlCmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
sqlCmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
sqlCmd.ExecuteNonQuery();
cn.Close();

UPDATE query on Access Database not working C#.NET

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);

Categories