I am trying to insert data into my SQL Server database in C#.
I am fairly new at programming, and would like to learn the correct way of doing so.
So far, I have a database class :
public SqlConnection connection()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "DESKTOP-UPVVOJP";
builder.InitialCatalog = "Lagersystem";
builder.IntegratedSecurity = true;
return new SqlConnection(builder.ToString());
}
Product class file :
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int ProductStock { get; set; }
public int ProductCategoryID { get; set; }
public int ProductEmployeeID { get; set; }
public DateTime ProductCreatedDate { get; set; }
// Constructor
public Product(string productname, int productstock, int productcategoryid, int productemployeeid)
{
ProductName = productname;
ProductStock = productstock;
ProductCategoryID = productcategoryid;
ProductEmployeeID = productemployeeid;
ProductCreatedDate = DateTime.Now;
}
}
Insert method in my program :
static void InsertProduct(string productname, int productstock, int productcategoryid, int productemployeeid)
{
Database db = new Database();
SqlConnection conn = db.connection();
using (SqlCommand command = new SqlCommand(@"INSERT INTO Products (ProductName, ProductStock, ProductCategoryID, ProductEmployeeID, ProductCreatedDate)
VALUES('{0}', {1}, {2}, {3}, '{4}')", conn))
{
string formattet = string.Format(productname, productstock, productcategoryid, productemployeeid, DateTime.Now);
Console.WriteLine(formattet);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
}
and my main method :
static void Main(string[] args)
{
while (true)
{
Console.Write("Indtast Produktnavn :");
string productname = Console.ReadLine();
Console.Write("Hvor mange er der på lager? : ");
int productstock = int.Parse(Console.ReadLine());
Console.Write("Hvilken kategori ID hører produktet til? : ");
int productcategoryid = int.Parse(Console.ReadLine());
Console.Write("Hvilket medarbejder ID har oprettet produktet? : ");
int productemployeeid = int.Parse(Console.ReadLine());
try
{
InsertProduct(productname, productstock, productcategoryid, productemployeeid);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
My database has the following setup :
CREATE TABLE Products
(
ProductID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
ProductName nvarchar(32) NOT NULL,
ProductStock INT,
ProductCategoryID INT,
ProductEmployeeID int NOT NULL,
ProductCreatedDate datetime NOT NULL DEFAULT GETDATE()
);
By running this, I can enter the data "productname, stock, categoryid, employeeid"
As "Jacket, 10, 1, 2" this should work as i have a category with the id 1. and a employee with the id 2.
When I run the program, I get an error
Incorrect syntax near '1'
My guess falls hard on some error in this area :
VALUES('{0}', {1}, {2}, {3}, '{4}')"
Jack O'Neill.