ConnectString在C#中不起作用 [英] ConnectString didn't work in C#

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

问题描述

public static DataSet ParseDatabaseData(string sheetName)
{
 string connectionString = "Provider=System.Data.SqlClient;Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;"; 

    SqlConnection conn = new SqlConnection(connectionString);

    string strSQL = "SELECT * FROM [" + sheetName + "$]";
    SqlCommand cmd = new SqlCommand(strSQL, conn);
    conn.Open();
    DataSet dataset = new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    adapter.Fill(dataset);
    conn.Close();
    return dataset;

}

错误显示‘provider’关键字错误。

The error show that 'provider' keyword is wrong.

请帮助我纠正如何通过连接字符串与数据库连接?

Please help me to correct how to connect with Database through connection string?

推荐答案

您可以将连接字符串放在web.config或app.config中,并在需要的地方使用配置,而不必在单个文件本身中提及连接字符串。

Instead of mentioning the connection string in the individual file itself, you can place the connection string in the web.config or app.config and use the config where ever required.

web.config 的示例将连接字符串放在< configuration> 下,您可以在其中提供提供商名称:

Sample for web.config place the connection string under the <configuration>, there you can provide the provider name:

<configuration>
    <connectionStrings>
       <add name="ConnString" 
            connectionString="Data Source= MHSPC56888_VM1\\SQLEXPRESS;Initial Catalog=xxxxxxx;User id=xx;Password=xxxxx;" 
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

并在文件内

public static DataSet ParseDatabaseData(string sheetName)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);

注意:使用System.Configuration添加表示 ConfigurationManager。

Note: add using System.Configuration; for the ConfigurationManager.

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

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