将文本框值插入数据库

inserting textbox values into database(将文本框值插入数据库)
本文介绍了将文本框值插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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

另外,如果你使用参数,你可以有一些类型安全,并且值将被正确地转换为 SQL Server.

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

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

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

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

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.

请参阅 此 MSDN 页面上的示例(SqlCommand.参数).

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

这篇关于将文本框值插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)