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.