inserting textbox values into database

前端 未结 6 1010
陌清茗
陌清茗 2020-12-16 07:57

im a newbie here and would like some advice on C# programming

i would like to store values from a textbox into a database. so far, i have the following:

<         


        
6条回答
  •  春和景丽
    2020-12-16 08:20

    At least your code should look like this:

    void SaveData(string projectName, DateTime biddingDueDate, string status, DateTime projectStartDate, string assignedTo, int pointsWorth, string staffCredits)
    {
        try
        {
            string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Customers.mdf;Integrated Security=True;User Instance=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandText = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES (@projectName, @biddingDueDate, @status, @projectStartDate, @projectStartDate, @assignedTo, @pointsWorth, @staffCredits)";
    
                command.Parameters.AddWithValue("@projectName", projectName);
                command.Parameters.AddWithValue("@biddingDueDate", biddingDueDate);
                command.Parameters.AddWithValue("@status", status);
                command.Parameters.AddWithValue("@projectStartDate", projectStartDate);
                command.Parameters.AddWithValue("@assignedTo", assignedTo);
                command.Parameters.AddWithValue("@pointsWorth", pointsWorth);
                command.Parameters.AddWithValue("@staffCredits", staffCredits);
    
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
        catch (SqlException ex)
        {
            Console.WriteLine(ex.Message);
        }
    
    }
    

    Parameter's type can be determined (tried to be) automatically:

    command.Parameters.AddWithValue("@biddingDueDate", biddingDueDate);
    

    or specified manually:

    command.Parameters.Add("@biddingDueDate", System.Data.SqlDbType.DateTime).Value = biddingDueDate;
    

    also you can convert date to string with specified format to minimize the risk of mistaken parsing (because of culture dependent specificity, etc) on database side:

    command.Parameters.Add("@biddingDueDate", System.Data.SqlDbType.DateTime).Value = biddingDueDate.ToString("yyyy-MM-dd"); // also you can use just yyyyMMdd
    

提交回复
热议问题