将文本框值插入数据库 [英] inserting textbox values into database

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

问题描述

我是这里的新手,想要一些关于 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).

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆