如何用SQL中的新列值替换列值? Asp.net C# [英] How can I replace my column values with new column values in SQL? Asp.net C#

查看:91
本文介绍了如何用SQL中的新列值替换列值? Asp.net C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨。

我用新的列值替换旧的列值,但我的查询没有执行,有时给我错误无效'tbl_field'但是tbl_field存在,tbl_field是我的表名。我怎么能解决这个问题。



我尝试了什么:



这是我的代码aspx.cs

Hi.
I'm replacing my old column values with new column values but my query is not executed and sometime give me error "invalid 'tbl_field' " but tbl_field is present,tbl_field is my table name.How can i resolve this issue.

What I have tried:

Here is my code aspx.cs

public void updateTbl(string newname)
    {
        string oldname = Session["oldname"].ToString();
        String db = Session["value"].ToString();
        SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS; Initial catalog=db_compiler; Integrated security=true");
        string RNquery="USE "+db+" EXEC sp_rename '"+oldname+"', '"+newname+"'";
        string updateQuery = "USE "+db+" Update 'tbl_field' SET Table_Name= replace(Table_Name, "+ oldname + ", " + newname + ")";
        SqlCommand cmd2 = new SqlCommand(updateQuery, cnn);
        SqlCommand cmd = new SqlCommand(RNquery, cnn);
        cnn.Open();
        cmd2.ExecuteNonQuery();//Here ERROR 'incorrect syntax near tbl_field
        cmd.ExecuteNonQuery();
       
        cnn.Close();
    }



我的'RNquery'用于更改数据库中的表名工作正常但发布'updateQuery'它给出了我的错误但是当我执行这个在sql中查询,它工作正常,我认为'或者'等有一些小错误。谢谢


My 'RNquery' which is used to change table name in database working fine but issue with 'updateQuery' its give my error but when i execute this query in sql ,it's working fine,i think there is some little mistake with ',or " etc.Thanks

推荐答案

Update 'tbl_field' 



我认为这应该是......


I think this should be...

Update tbl_field 


试试这个



try this

string updateQuery = "USE " + db + " Update tbl_field SET Table_Name= replace(Table_Name, '" + oldname + "', '" + newname + "')";





但是在c#中构建一个sql语句很容易出现 SQL注入攻击,如果你得到的话来自用户的输入值,而不是你应该使用SQL参数

参考这些文章



SQL注入 [ ^ ]

SQL注入攻击以及如何防范它们的一些技巧 [ ^ ]

SQL注入预防备忘单 - OWASP [ ^ ]



but framing an sql statement in c# is prone to SQL injection attacks, if you are getting the input values from user, instead you should use SQL Parameters
refer these articles

SQL Injection[^]
SQL Injection Attacks and Some Tips on How to Prevent Them[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]


如果你想使用它数据库,你有一个连接字符串然后为什么要使用'use'语句,基本上它用于将数据库上下文更改为SQL Server中的指定数据库或数据库快照。删除'使用'并重试
if you want to use same database and you have a connection string then why to use 'use' statement, basically it use to Changes the database context to the specified database or database snapshot in SQL Server. remove 'use' and try again


这篇关于如何用SQL中的新列值替换列值? Asp.net C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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