将文本框值插入数据库

发布于 2024-09-30 23:04:21 字数 786 浏览 5 评论 0原文

我是这里的新手,想要一些有关 C# 编程的建议,

我想将文本框中的值存储到数据库中。 到目前为止,我有以下内容:

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

代码中没有错误,但我似乎无法弄清楚为什么数据库中没有存储任何内容。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

南渊 2024-10-07 23:04:21

首先,您的代码已经适合SQL 注入攻击 - 您确实应该使用参数化查询。

另外,如果使用参数,则可以具有一定的类型安全性,并且值将被正确转换到 SQL Server。

很难判断这里出了什么问题,因为我们不知道您连接的值(例如,bidDueDate 是什么样的?,thisQuery 是什么样的)在执行之前?)。

我通常会将其编写为存储过程,获取插入记录所需的参数,在我的 C# 中,我将创建命令对象,并向其添加正确的参数(和类型)。

请参阅 MSDN 页面 (SqlCommand.Parameters) 上的示例。

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).

oО清风挽发oО 2024-10-07 23:04:21

至少您的代码应该如下所示:

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

}

参数的类型可以自动确定(尝试):

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

或手动指定:

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

您还可以将日期转换为具有指定格式的字符串,以尽量减少错误解析的风险(由于文化相关的特殊性等) )在数据库端:

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

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
ヤ经典坏疍 2024-10-07 23:04:21

如果示例中的变量是 TextBox,则应写为 projName.Text、status.Text。

If the variable in example is TextBox that it should write like projName.Text, status.Text.

迟月 2024-10-07 23:04:21

您是否将数据库文件的“复制到输出目录”属性设置为“始终复制”?

因为这会在每次构建时覆盖您的数据库文件。

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.

梅窗月明清似水 2024-10-07 23:04:21

如果您的 ProjectStartDate 和日期通常是数据库中的日期时间值,那么在插入带有 '.
它应该是这样的:

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

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+"')"; 
娇纵 2024-10-07 23:04:21

要找出问题所在,您要做的第一件事就是放在

Console.WriteLine(thisQuery);

StringthisQuery= 行之后,

这将准确地显示您正在使用什么语句调用 Db,并且只需查看即可清楚在输出中该语句有什么问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文