当我尝试登录我的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);
任何帮助将不胜感激。
谢谢。
答案 0 :(得分:0)
首先请分享整个代码,或者请检查您是否正在尝试打开已关闭的连接。