Xboxbo
Xboxbo

Reputation: 69

sql statement does not work on specific table

I Have a website which creates new order and saves shopping bag items into database. The thing is that insert into,select,update,delete sentences are working in all my tables except one, i think i wrote the sentence perfectly but its still throw excption that says something wrong with the sentence.

string OrderSql = string.Format(@"
    INSERT INTO Order ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend]) 
    VALUES ({0},{1},{2},{3},'{4}')",
 UserId, DateTime.Now, Price, 1, Address);

at first i thought the problem may be found at the db so i copied my db into new once still doesnt working i would send the relationship between tables but i need 10 rep..

Upvotes: 0

Views: 77

Answers (2)

MethodMan
MethodMan

Reputation: 18843

you can also create a method call it and do something like this. This would require that you create a stored procedure with the @Parameters shown in this example ** if this is Access then petelids Answer will be a great starting point if this is SQL Server then what I have posted would work for you

private void InsertMyData(string UserId, DateTime DayMonthYear, double Price, string Address)
{ 
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO [Order] ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend]) 
                                         VALUES (@UserId, @DayMonthYear, @Price, 1, @Address)";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = connection;
        cmd.Parameters.AddWithValue("@UserId", UserId);
        cmd.Parameters.AddWithValue("@DayMonthYear", DayMonthYear);
        cmd.Parameters.AddWithValue("@PriceToPay", Price);
        cmd.Parameters.AddWithValue("@StatusID", 1);
        cmd.Parameters.AddWithValue("@AdressToSend", Adress);
        connection.Open();
        cmd.ExecuteNonQuery();
    }
}

Upvotes: 1

petelids
petelids

Reputation: 12815

It looks like you have two issues. Firstly as @juergen points out in the comments order is a reserved word so you'll need to enclose it in square brackets. Secondly, you don't have the date enclosed in quotes. So your code should read:

string OrderSql = string.Format(@"INSERT INTO [Order] ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend]) 
VALUES ({0},'{1}',{2},{3},'{4}')", UserId, DateTime.Now, Price, 1, Address);

Note the square brackets around Order and the single quotes around {1}.

However, you are open to SQL Injection attacks using that code so I would strongly suggest you read up on using parameterized queries. @DJ KRAZE has added a link in the comments to this question which should point you in the right direction.

Upvotes: 1

Related Questions