Michael Bowman
Michael Bowman

Reputation: 245

Insert adding items to wrong column

Below is an insert statement that is inputting the first value (acctNum) into the second column (itemCode) and vice versa:

string addUpcCode = "INSERT INTO compare1 (acct, itemcode)"
                    + "VALUES ('"+acctNum+"', '"+itemCode+"')";

This is not how I want it to work, as I want the first value to go in the first column and the second in the second column. How can I go about this?

Side note: This is a rough draft until I learn more about parameterization. I won't be releasing this code until I learn and implement it.

Upvotes: 0

Views: 90

Answers (4)

coderoaq
coderoaq

Reputation: 39

Use parametrized queries to prevent SQL injection and you can solve this matter

 command.Parameters.Add("AcctNum", acctNum);

Upvotes: 0

Eugen Rieck
Eugen Rieck

Reputation: 65284

The given SQL snipplet will do what you want - especially the sequence of columns will be preserved.

I suspect you might have switched your variables, leading to the same phenomen but out of an other reason.

Upvotes: 1

Daniel Flippance
Daniel Flippance

Reputation: 7932

You should use SQL Parameters which also avoids creating a SQL injection problem:

using (SqlCommand command = new SqlCommand("INSERT INTO compare1 (acct, itemcode) VALUES (@AcctNum, @ItemCode)", connection))
{
    // Add new SqlParameter to the command.
     command.Parameters.Add(new SqlParameter("AcctNum", acctNum));
     command.Parameters.Add(new SqlParameter("ItemCode", itemCode));

Upvotes: 1

Mikey Mouse
Mikey Mouse

Reputation: 3098

As you're using C# the string.format function is perfect for this kind of thing

    string.format("INSERT INTO compare1(acct, itemCode) Values('{0}','{1}'", acctNum, itemCode);

or

    string.format("INSERT INTO compare1 SELECT '{0}','{1}' ", acctNum, itemCode);

But yeah, you probably have them mixed up somewhere else, the order will be kept. Oh and if acctNum is an integer, you won't need the quotation marks around {0}

Edit: Oh and yeah, definitely look into parameters next

Upvotes: 0

Related Questions