我有一個登錄表單在我的項目,我寫下面的代碼附加我的數據庫(存在d:\)時,此登錄窗體加載:附加數據庫編程
try
{
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=master;Integrated Security=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from sys.databases", con);
DataTable dt = new DataTable();
da.Fill(dt);
string[] array = dt
.AsEnumerable()
.Select(row => row.Field<string>("Name"))
.ToArray();
if (!array.Contains("cstmrDB", StringComparer.OrdinalIgnoreCase))
{
SqlCommand cmd = new SqlCommand("sp_attach_db");
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@dbname", "Apdb");
cmd.Parameters.AddWithValue("@filename1", @"d:\Apdb.mdf");
cmd.ExecuteNonQuery();
}
}
catch (exception ex)
{
messagebox.show(ex.message);
}
它工作正常,在我的筆記本電腦。我發佈我的項目(使用c#發佈)並安裝SQL Server和我的項目,並將我的數據庫複製到另一臺PC的d:\中。但是當我運行我的項目時,數據庫不會附加!我不知道爲什麼會出現這個問題......但我想也許是因爲我沒有編寫任何代碼來定義* .ldf文件(但我把ddf和mdf都放在d:\中)
ERROR: A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
你有沒有收到任何錯誤? –
嗯,是的,基本的調試技巧真的很難得到。首先捕獲異常並查看SQL Server日誌以查看發生了什麼。我很確定這個電話不會奇蹟般地無所事事。 – TomTom
@DynamicVariable問題已更新 – Ali