将c#字符串变量与SQL语句一起使用 [英] Using c# string variable with a SQL statement

查看:185
本文介绍了将c#字符串变量与SQL语句一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,在C#中,我想在SQL语句中使用字符串变量,但是我收到错误。

Hello, in C#, i want to use a string variable inside a SQL statement yet i get error.

//...
SqlCommand cmd = new SqlCommand(@"USE " + DatabaseNameString + @" GO", connectionString);
connectionString.Open();
SqlDataReader rdr = cmd.ExecuteReader();//Gets Exception here
//...



任何想法怎么解决这个问题?感谢帮助。


Any ideas how to fix this? Appreciating the help.

推荐答案

你的SQL语句毫无意义,也不会返回任何内容。



你所做的只是说USE thisDatabase GO,这在SQL中没有任何意义。你根本没有执行任何查询。



你想做什么?
You SQL statements make no sense and don't return anything.

All you did was say "USE thisDatabase GO", which doesn't make any sense in SQL. You didn't execute any query at all.

What are you trying to do??


你不能使用 GO SqlCommand ;它是一个批处理分隔符,只能由SQL Server Management Studio和相关的命令行工具识别。使用ADO.NET,您只需将每个批处理作为单独的命令发出。



您尝试执行的命令不会返回任何记录。因此, ExecuteReader 是错误的使用方法。请尝试 ExecuteNonQuery



最后,如果您只想更改<$ c的当前数据库$ c> SqlConnection ,尝试 ChangeDatabase 方法 [ ^ ]:

You can't use GO in a SqlCommand; it's a batch separator which is only recognized by SQL Server Management Studio and associated command-line tools. With ADO.NET, you just issue each batch as a separate command.

The command you're trying to execute doesn't return any records. Therefore, ExecuteReader is the wrong method to use. Try ExecuteNonQuery instead.

And finally, if you just want to change the current database for a SqlConnection, try the ChangeDatabase method[^]:
using (SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE"))
{
    connection.Open();
    connection.ChangeDatabase(DatabaseNameString);
    ...
}


这篇关于将c#字符串变量与SQL语句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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