Console.WriteLine("++++++++ Fun with Data Readers AutoLot++++++++++++\n");
// create and open connection
using (SqlConnection connect = new SqlConnection())
{
connect.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=
C:\Users\serge\AutoLot.mdf;Integrated Security=True;Connect Timeout=30";
connect.Open();
// create object SQL command
string sql = "Select * From Inventory";
SqlCommand myCommand = new SqlCommand(sql, connect);
// get object of data reading with ExecuteREader ()
using (SqlDataReader myDataReader = myCommand.ExecuteReader())
{
// iterate loop results
while (myDataReader.Read())
{
Console.WriteLine($"-> Make : {myDataReader["MakeId"]},\t " +
$"PetName : {myDataReader["PetName"]},\t" +
$" Color : {myDataReader["Color"]}.");
}
}
}
Console.WriteLine();
Console.WriteLine("============= Fun with Data Readers Northwind DB =============\n");
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=
C:\Users\serge\AppData\Local\Microsoft\Microsoft SQL Server
Local DB\Instances\MSSQLLocalDB\northwnd.mdf;Integrated Security=True;Connect Timeout=30";
connection.Open();
string sql = "Select * From Products ";
SqlCommand myCommand1 = new SqlCommand(sql, connection);
/* SqlConnection nwrdConnection = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindDB"].ConnectionString);
nwrdConnection.Open();
SqlCommand myCommand1 = new SqlCommand(sql, nwrdConnection);*/
using (SqlDataReader myDataReader1 = myCommand1.ExecuteReader())
{
while (myDataReader1.Read())
{
Console.WriteLine($"===> ProductName : {myDataReader1["ProductName"]},\t" +
$"CategoryId : {myDataReader1["CategoryID"]},\t" +
$"UnitsInStock : {myDataReader1["UnitsInStock"]}");
}
}
}
Console.ReadLine();
The second query generates an exception :
Unhandled Exception: System.Data.SqlClient.SqlException: An attempt to attach an auto-named database for file C:\Users\serge\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB\northwnd.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
While using debug mod it throws an exception in method:
connection.Open();
PS: uncommenting the other version of connection with adding connection string in app.config
works fine.
I really don't understand why because connection to the first query works fine without any changes in app.config
.