Question

For some reasons, I am unable to establish a data connection using my connection string. I was doing with the below code

var connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection(connectionString);
cmd.Connection = connectionString;

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = " dbo.SelectAll";

SqlParameter param = new SqlParameter("@tradeDate","201401");

param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);

But for some reasons when I am initializing the connection property to my command using cmd.Connection = connectioString, is is throwing an exception as follows

Cannot implicitly convert type 'string' to 'System.Data.SqlClient.SqlConnection'

Was it helpful?

Solution

You're confusing the connection string needed to connect to the database and the actual SqlConnection.

try this (for your specific code):

cmd.Connection = con;

According to MSDN here is a proper example:

private static void CreateCommand(string queryString, string connectionString)
 {
    using (SqlConnection connection = new SqlConnection(connectionString))
     {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

Link to original article: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx

OTHER TIPS

I think you need just

cmd.Connection = con;

You are try to do set your SqlCommand.Connection property with your connection string. But this property is for specify your SqlConnection object, not your connection string.

From documentation;

Gets or sets the SqlConnection used by this instance of the SqlCommand.

And since there is no implicit conversation from SqlConnection to string, that's why you get compile time error.

As a side note, use using statement to dispose your SqlConnection and SqlCommand like;

using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand())
{
   cmd.Connection = con;
   ...
   ...
}

or you can use SqlConnection.CreateCommand() method to create your SqlCommand associated your SqlConnection inside your using statement like;

using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
   ...
   ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top