如何在c#中使用更新查询 [英] how to use update query in c#

查看:64
本文介绍了如何在c#中使用更新查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行

 cmd.CommandText =   update onlineUsers set status =' + true +  'where username =' + txtUsername.Text +  '; 



在上面的查询中我收到一个错误,上面写着:

 System.Data.dll中出现'System.Data.SqlClient.SqlException'类型的异常但未在用户代码中处理

附加信息:'('。

解决方案

附近的语法不正确,它是提供问题的用户名。

但是......你不应该这样做。不要连接字符串来构建SQL命令。它让你对意外或故意的SQL注入攻击敞开大门这可能会破坏整个数据库。请使用参数化查询。

Th很有可能解决这个问题也会解决你的其他问题,以及让你的代码更容易阅读。

 cmd.CommandText =   update onlineUsers set status = @ STAT where username = @ UN; 
cmd.Parameters.AddWithValue( @ STAT true);
cmd.Parameters.AddWithValue( @ UN,txtUsername.Text);


I am trying to execute

cmd.CommandText = "update onlineUsers set status='"+true+"' where username='"+txtUsername.Text+"'";


In the above query I am getting an error which says:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near '('.

解决方案

Probably, it's the username that's giving the problem.
But...you shouldn't do 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.
The chances are that fixing that will also solve your other problem, as well as making your code easier to read.

cmd.CommandText = "update onlineUsers set status=@STAT where username=@UN";
cmd.Parameters.AddWithValue("@STAT", "true");
cmd.Parameters.AddWithValue("@UN", txtUsername.Text);


这篇关于如何在c#中使用更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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