C#中的SqlConnection [英] SqlConnection in C#

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

问题描述

在 VB.NET 中我可以使用:

In VB.NET I can use:

Protected Conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Active").ConnectionString)

但是,当我在 C# 中执行以下操作时:

However, when I do the following in C#:

protected SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings("conn"));

我收到错误:

名称ConfigurationManager"在当前上下文中不存在

The name 'ConfigurationManager' does not exist in the current context

如果我把它改成:

protected SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("conn"));

我收到错误:

不可调用成员'System.Configuration.ConfigurationManager.ConnectionStrings' 不能像方法一样使用.

Non-invocable member 'System.Configuration.ConfigurationManager.ConnectionStrings' cannot be used like a method.

这是为什么,我如何使用 C# 连接到我的 SQL Server 数据库?

Why is this and how can I connect to my SQL Server database using C#?

推荐答案

试试这个:

protected SqlConnection conn = new SqlConnection(
    ConfigurationManager.ConnectionStrings["conn"].ConnectionString
);

注意 [] 而不是 () ,后者用于访问 C# 中的数组元素.还要注意 .ConnectionString 属性调用的用法,因为 SqlConnection 构造函数需要一个字符串.

Notice the [] instead of () which is what is used to access an element of an array in C#. Also notice the usage of the .ConnectionString property call as the SqlConnection constructor expects a string.

这篇关于C#中的SqlConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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