ConnectString didn't work in C#

。_饼干妹妹 提交于 2019-12-23 13:02:43

问题


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;

}

The error show that 'provider' keyword is wrong.

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


回答1:


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.

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>

and inside the file

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

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




回答2:


You do not need to specify the Provider in the Connection String.

Try it like this:

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


来源:https://stackoverflow.com/questions/50167007/connectstring-didnt-work-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!