Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection string not working in C# windows application

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'

like image 851
DoIt Avatar asked Jan 24 '26 02:01

DoIt


1 Answers

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

like image 98
Pseudonym Avatar answered Jan 25 '26 17:01

Pseudonym