user3032509
user3032509

Reputation: 73

How to build a SQL connection string dynamically at run time?

I'm uploading the .mdf files at runtime to the application and when i upload a file i create a SQL connection string when the upload finish so i can save it to my database, then i'm trying to connect to the mdf file that i've uploaded before but i have many error (depending on the connection string that i try).

Here the connection that i've tried:

string sqlConn= @"Data Source=localhost;AttachDbFilename=" + destPath + ";Integrated Security=True;Connect Timeout=30";

string cadena =@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + destPath + ";Integrated Security=True;Connect Timeout=30; User Instance=True";

string cadena = "Server=.\SQLExpress;AttachDbFilename=" +  sqlPath +";Database=" + dbName + ";Trusted_Connection = Yes;"

destPath is the route where the .mdf stores and locate at my server(pc), next i save "sqlConn" to my own db and next i try to connect to get some data from the uploaded db, i don't know if i'm wrong trying to use "localhost" as server but i got nothing else on mind.

Here's the code:

var q = (from sql in bd.C_SQL
         where sql.id_empresa == idEmp && sql.Periodo == mes && sql.Status == 1
         select sql.sql_string).FirstOrDefault();

        string cuentas = "select cu.Codigo as 'Codigo', cu.Nombre as 'Descripcion', SUM(po.Abonos) as 'Monto' from Cuentas cu inner join MovimientosPoliza mp on cu.Id = mp.IdCuenta inner join Polizas po on mp.IdPoliza = po.Id where cu.Codigo like '" + opcion +"%' and mp.Ejercicio = 2015 and mp.Periodo = " + mes + " group by cu.Codigo, cu.Nombre";
        int x = 0;
        using(SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = q;
            conn.Open();

            SqlCommand query = new SqlCommand("cuentas ", conn);
            using(SqlDataReader reader = query.ExecuteReader())
            {
                while(reader.Read())
                {
                    x++;
                }
            }
        }

Everything failed on Open(). 1.- Error: A file with same name exist, cannot access file, it's located at UNC share. 2.- Error: Login failed for user.

Any help? please

Upvotes: 0

Views: 308

Answers (1)

user3032509
user3032509

Reputation: 73

Answer was very simple, the DataSource can't be ".\SQLEXPRESS" because the uploaded mdf's stores at the App_Data folder, so i just modify to:

string cadena = @"Server=(localdb)\v11.0;AttachDbFilename=" + destPath + ";Database=" + nombreBd + ";Trusted_Connection = Yes;";

And eveything works just fine

Upvotes: 1

Related Questions