0
嘗試登錄到我的asp.net網站的管理部分時,我得到以下錯誤:試圖附加自動命名的數據庫文件失敗
試圖附加自動命名的數據庫文件C:\ Users \ joshy \ Documents \ Visual Studio 2015 \ WebSites \ nas2 \ App_Data \ nas.mdf失敗。具有相同名稱的數據庫存在,或指定的文件無法打開,或位於UNC共享上。
**它突出反映了以下幾行代碼在我connectionclass.cs
文件:**
Line 113: try
Line 114: {
Line 115: conn.Open();
Line 116: int amountOfUsers = (int)command.ExecuteScalar();
這裏是連接class.cs文件的用戶部分的代碼:
#region Users
public static User LoginUser(string name, string password)
{
//Check if user exists
string query = string.Format("SELECT COUNT(*) FROM nas.dbo.users WHERE name = '{0}'", name);
command.CommandText = query;
try
{
conn.Open();
int amountOfUsers = (int)command.ExecuteScalar();
if (amountOfUsers == 1)
{
//User exists, check if the passwords match
query = string.Format("SELECT password FROM users WHERE name = '{0}'", name);
command.CommandText = query;
string dbPassword = command.ExecuteScalar().ToString();
if (dbPassword == password)
{
//Passwords match. Login and password data are known to us.
//Retrieve further user data from the database
query = string.Format("SELECT email, user_type FROM users WHERE name = '{0}'", name);
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
User user = null;
while (reader.Read())
{
string email = reader.GetString(0);
string type = reader.GetString(1);
user = new User(name, password, email, type);
}
return user;
}
else
{
//Passwords do not match
return null;
}
}
else
{
//User does not exist
return null;
}
}
finally
{
conn.Close();
}
}
public static string RegisterUser(User user)
{
//Check if user exists
string query = string.Format("SELECT COUNT(*) FROM users WHERE name = '{0}'", user.Name);
command.CommandText = query;
try
{
conn.Open();
int amountOfUsers = (int)command.ExecuteScalar();
if (amountOfUsers < 1)
{
//User does not exist, create a new user
query = string.Format("INSERT INTO users VALUES ('{0}', '{1}', '{2}', '{3}')", user.Name, user.Password,
user.Email, user.Type);
command.CommandText = query;
command.ExecuteNonQuery();
return "User registered!";
}
else
{
//User exists
return "A user with this name already exists";
}
}
finally
{
conn.Close();
}
}
#endregion
更多的connectionclass.cs代碼:
using System.Collections;
using System.Configuration;
using System.Data.SqlClient;
using Entities;
public static class ConnectionClass
{
private static SqlConnection conn;
private static SqlCommand command;
private static object toursdate;
static ConnectionClass()
{
string connectionString = ConfigurationManager.ConnectionStrings["nas_connect"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
任何幫助將不勝感激。
謝謝。
我已經解決了這個問題,分享了更多的代碼。我該如何檢查連接是否關閉?謝謝@sarat – jmc1690
你如何檢查連接即時試圖打開是否關閉? – jmc1690
http://s32.postimg.org/r82ih8ak5/connection.jpg會這表明連接即時嘗試打開是封閉的? – jmc1690