简体   繁体   中英

inserting textbox values into database

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:

string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Customers.mdf;Integrated Security=True;User Instance=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

string query = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES ('"+projName+"', '"+bidDueDate+"', '"+status+"', '"+projectStartDate+"', '"+projectEndDate+"', '"+assignedTo+"', '"+pointsWorth+"', '"+aStaffCredits+"')";
SqlCommand command = new SqlCommand(query, connection);

command.ExecuteNonQuery();
connection.Close();

There are no errors in the code, but i cannot seem to figure out why nothing is being stored in the database.

First, your code is ripe for SQL Injection attacks - you really should be using parameterized queries.

Also, if you use parameters, you can have some type safety and the values will be translated correctly to SQL Server.

It is difficult to tell what is wrong here, since the values you are concatenating are unknown to us (for instance, what does bidDueDate look like?, What does thisQuery look like before you execute it?).

I would normally write this as a stored procedure taking the parameters you need for inserting a record, in my C# I would create the command object add the correct parameters (and types) to it.

See the example on this MSDN page (SqlCommand.Parameters).

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

如果示例中的变量是TextBox,它应该像projName.Text,status.Text一样编写。

Do you have 'Copy to Output Directory' property set to 'Copy Always' for the database file?

Because this would overwrite your database file everytime you build.

the first thing you want to do to find out what's going wrong is put

Console.WriteLine(thisQuery);

after the line StringthisQuery=

This will show you exactly what statement you're calling the Db with, and it may be clear just from looking at the output what's wrong with the statement.

if your ProjectStartDate and dates in general are datetime values in the DB, then you will get an error when inserting data with the '. It should be like:

String thisQuery = "INSERT INTO ProjectList (ProjectName, BiddingDueDate, Status, ProjectStartDate, ProjectEndDate, AssignedTo, PointsWorth, StaffCredits) VALUES ('"+projName+"', "+bidDueDate+", '"+status+"', "+projectStartDate+", "+projectEndDate+", '"+assignedTo+"', '"+pointsWorth+"', '"+aStaffCredits+"')"; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM