使用 C# INSERT INTO SQL 服务器数据库的问题

Problem with INSERT INTO SQL Server database using C#

我正在尝试用 C# 将数据插入我的 SQL 服务器数据库。

我是编程新手,想学习正确的编程方法。

到目前为止,我有一个数据库 class :

public SqlConnection connection()
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "DESKTOP-UPVVOJP";
    builder.InitialCatalog = "Lagersystem";
    builder.IntegratedSecurity = true;

    return new SqlConnection(builder.ToString());
}

产品class文件:

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;
    }
}

在我的程序中插入方法:

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();
    }
}

和我的主要方法:

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();
        }
    }
}

我的数据库具有以下设置:

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()
);

通过运行这个,我可以输入数据“productname, stock, categoryid, employeeid”

作为“夹克,10、1、2”,这应该可以工作,因为我有一个 ID 为 1 的类别和一个 ID 为 2 的员工。

当我运行程序时,我得到一个错误

Incorrect syntax near '1'

我的猜测与这方面的一些错误有关:

VALUES('{0}', {1}, {2}, {3}, '{4}')"

我建议使用查询参数,如下所示:

conn.Open();

SqlCommand command = new SqlCommand(
    @"INSERT INTO Products
        (ProductName, ProductStock, ProductCategoryID, ProductEmployeeID, ProductCreatedDate)
        VALUES(@ProductName, @ProductStock, @ProductCategoryID, @ProductEmployeeID, getDate())", 
    conn
);
command.Parameters.Add("@ProductName", productname);
command.Parameters.Add("@ProductStock", productstock);
command.Parameters.Add("@ProductCategoryID", productcategoryid);
command.Parameters.Add("@ProductEmployeeID", productemployeeid);

command.ExecuteNonQuery();
conn.Close();

请注意,您可以直接在查询中计算当前 date/time,使用 SQL 服务器函数 getDate() 而不是从 c# 传递它。

谢谢,通过使用这种正确的方法,它的工作完美无缺。你摇滚!

        static void InsertProduct(string productname, int productstock, int productcategoryid, int productemployeeid)
        {
            Database db = new Database();
            SqlConnection conn = db.connection();
            conn.Open();
            using SqlCommand command = new SqlCommand(@"INSERT INTO Products
                (ProductName, ProductStock, ProductCategoryID, ProductEmployeeID, ProductCreatedDate)
                VALUES(@ProductName, @ProductStock, @ProductCategoryID, @ProductEmployeeID, getDate())",conn);
            {
                command.Parameters.Add(new SqlParameter("@ProductName", productname));
                command.Parameters.Add(new SqlParameter("@ProductStock", productstock));
                command.Parameters.Add(new SqlParameter("@ProductCategoryID", productcategoryid));
                command.Parameters.Add(new SqlParameter("@ProductEmployeeID", productemployeeid));

                command.ExecuteNonQuery();
                conn.Close();
            }
        }