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).
这篇关于将文本框值插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将文本框值插入数据库


- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01