0

I am trying to add new record to the SQL Database Table using class Object. I create a list of Products and then iterate through all of them with sql statement.

My code is like this:

    private void backupButton_Click(object sender, RoutedEventArgs e)
    {
        ReadAllProductsList dbproducts = new ReadAllProductsList();
        DB_Product = dbproducts.GetAllProducts();
        List<Product> SQLProductList = new List<Product>();
        SQLProductList = DB_Product.Where(Product => Product.UserId == currentUser).ToList();
        for(int i = 0; i < SQLProductList.Count; i++)
        {
            InsertSQLProduct(new Product(SQLProductList[i].UserId,
                                                        SQLProductList[i].Name));

        }
    }

    public void InsertSQLProduct(Product objProduct)
    {
        using (var connection = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated Security=SSPI;database=MyLocalDB"))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand("INSERT INTO Product (UserId, Name) '" +
                                                        "'VALUES (null, '" + objProduct.Name + "');", connection))
            {
                command.ExecuteNonQuery();
            }

        }
    }

And the Product class looks like this:

public class Product
{

    // List<DietId> Lst = new List<DietId>();
    //The Id property is marked as the Primary Key  
    [SQLite.Net.Attributes.PrimaryKey, SQLite.Net.Attributes.AutoIncrement]
    public int Id { get; set; }
    public string UserId { get; set; }
    public string CreationDate { get; set; }
    public string Name { get; set; }




    public override string ToString()
    {
        return Name;
    }

    public Product()
    {
        //empty constructor  
    }

    public Product(string userId, string name)
    {
        UserId = userId;

        CreationDate = DateTime.Now.ToString();

        Name = name;

    }
}

However, I get error on command that says:

syntax error near '.'

What am I doing wrong here?

PS. The Name in SQL is of VARCHAR type.

EDIT: I have used parameter and converted the string to varchar and now I get different error:

String or binary data would be truncated. The statement has been terminated

OK. Sorted.

The last error tells me that the column was accepting only 1 character as 1 is default for VARCHAR.

I recreated tables with new max input for records.

Using parameters has solved my original problem.

Thank you guys.

5
  • 2
    Parameterize your sql. Don't concatenate it together. You also have some strangely placed single quotes Commented Jun 20, 2018 at 16:28
  • I will, I am writing without parameters for testing. Commented Jun 20, 2018 at 16:28
  • Have a look at this little bobby tables as well Commented Jun 20, 2018 at 16:31
  • 1
    Test with parameterized queries though. They fix a lot of problems that concatenation causes. They are also JUST as easy to write. You may fix your apostrophe/single-quote issue and find that the value you are concatenating is bringing in unexpected garbage that causes the SQL to fail. Commented Jun 20, 2018 at 16:31
  • yes, I will. I use parameters, here I didn't use them yet as I am testing the code. Commented Jun 20, 2018 at 16:32

2 Answers 2

7
"INSERT INTO Product (UserId, Name) '" +
"'VALUES (null, '" + objProduct.Name + "');",

There are extra apostrophes: one at the end of the first line, one at the start of the second.

Also, use a parameter to avoid SQL injection attack, either intentionally or unintentionally. It could be causing your error, depending on what the value is in objProduct.Name.

Sign up to request clarification or add additional context in comments.

Comments

1

You have extra single quotes. Your SQL query works out to INSERT INTO Product (UserId, Name) ''VALUES (null, 'name')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.