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

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

问题描述

我是一个新手在这里,并想在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();

有在code没有错误,但我似乎无法找出为什么没有被存储在数据库中。

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

推荐答案

首先,你的code是成熟 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.

请参阅<一个例子href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx">this MSDN页面(SqlCommand.Parameters)。

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

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

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