Search code examples
c#sqlconnection

SqlConnection() exception


i am having following trouble with this code.

unhandled exception of type 'System.ArgumentException' occurred in System.Data.Dll

static void Main(string[] args)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\MUHAMMAD\DOCUMENTS\SAMEE.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
        SqlCommand cmd = new SqlCommand("Select * from Student", con);
        con.Open();
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Console.WriteLine("{0}", dr[0].ToString());
        }
        Console.ReadKey();
    }

Solution

  • Problem: You have single quote &quot before and after the Database filename .
    Solution : you don't need to provide single quote &quot for database file name.so remove the &quot before and after the database filename.

    Try This:

    con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\MUHAMMAD\DOCUMENTS\SAMEE.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
    

    EDIT :

    if your table name is Table you should enclose it in square brackets [] as it is a Reserved word in SQL-Server.

    Try This:

     SqlCommand cmd =  new SqlCommand("Select * from [Table]",con );
    

    Solution 3: you need to use while loop to display all values.

    static void Main(string[] args)
    {
    SqlConnection con = new SqlConnection();
    con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\MUHAMMAD\DOCUMENTS\SAMEE.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
    SqlCommand cmd =  new SqlCommand("Select * from [Table]",con );
    con.Open();
    SqlDataReader dr;
    dr = cmd.ExecuteReader();
    while(dr.Read())
    {
    Console.WriteLine("{0}",dr[0].ToString());
    }
    Console.ReadKey(); 
    }