如何在C#中插入SQL参数的值 [英] How to insert SQL parameter's value in C#

查看:136
本文介绍了如何在C#中插入SQL参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string equery =插入离开(UserId,leaveType,seasonLeave,Reason)值(@UserId,'+ leavetype.Text.ToString()。Trim()+',@ seaonleave,' + reason.Text.ToString()。修剪()+');



此查询中的位置 UserId是外键,我如何在C#中调用 @UserId

string equery = "Insert into leave(UserId,leaveType,seasonLeave,Reason)values(@UserId,'" + leavetype.Text.ToString().Trim() + "',@seaonleave,'" + reason.Text.ToString().Trim() + "')";

Where in this query UserId is an foreign key, how i call the @UserId in the C#.

推荐答案

使用以下命令为命令参数添加参数:

command.Parameters.AddWithValue(...)



给出查询字符串的示例:
Add parameters to your Command Parameters using:
command.Parameters.AddWithValue(...)

Example Given with your query string:
string equery = "Insert into leave(UserId,leaveType,fromDate,toDate,numdays,seasonLeave,Reason)values(@UserId,'" + leavetype.Text.ToString().Trim() + "',@seaonleave,'" + reason.Text.ToString().Trim() + "')";

SqlConnection connection = new SqlConnection(MyConnectionString);
SqlCommand command = new SqlCommand(equery , connection);

// Adding the value to the parameter "UserID"
command.Parameters.AddWithValue("UserId", txtUserID.Text); 

// Add all your parameters this way ... 





干杯,

Edo



Cheers,
Edo


你不打电话给你 - 你需要提供它作为参数。当你这样做时,不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。改为使用参数化查询。



You don't call it - you need to provide it as a parameter. And while you are doing that, do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead throughout.

string equery = "INSERT INTO leave (UserId, leaveType, fromDate, toDate, numdays, seasonLeave, Reason) VALUES(@UserId, @Type, xx, xx, xx, @seaonleave, @Reason)";
using (SqlCommand cmd = new SqlCommand(equery, con))
   {
   cmd.Parameters.AddWithValue("@UserId", myUserId);
   cmd.Parameters.AddWithValue("@Type", leavetype.Text.Trim());
   ... // Continue here with more parameters and so forth
   }

我添加了xx部分,以指示您需要在原始文件中指定错过的数据 - 如果您没有,SQL会抱怨;为您列出的列提供足够的值。

I added the "xx" parts to indicate where you need to specify data that you missed in your original - SQL will complain if you don;t supply sufficient values for the columns you listed.


这篇关于如何在C#中插入SQL参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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