我正在尝试从数据库中获取用户角色。
这有效,它只是一个调试
public String GetRole()
{
string role = "";
string querySQL = "SELECT * FROM Utilizadores WHERE Role LIKE 'admin' ";
List<Users> lista = new List<Users>();
try
{
//Cria uma instância de ligação à base de dados SQL Server Express
conn = new SqlConnection(ligacaobd);
//Abre a ligação à base de dados
conn.Open();
//Executa a instrução SQL
SqlCommand cmd = new SqlCommand(querySQL, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
lista.Add(new Users(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3)));
role = reader.GetString(3);
}
}
catch (SqlException)
{
return role;
}
finally
{
conn.Close();
}
return role;
}
我将其放在一个按钮中,当我单击它时,它将标签更改为“ admin”。
我想要什么
public String GetRole(string username)
{
string role = "";
string querySQL = "SELECT" +@username+ "FROM Utilizadores";
List<Users> lista = new List<Users>();
try
{
//Cria uma instância de ligação à base de dados SQL Server Express
conn = new SqlConnection(ligacaobd);
//Abre a ligação à base de dados
conn.Open();
//Executa a instrução SQL
SqlCommand cmd = new SqlCommand(querySQL, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
lista.Add(new Users(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3)));
role = reader.GetString(3);
}
}
catch (SqlException)
{
return role;
}
finally
{
conn.Close();
}
return role;
}
我想获得传入的用户名角色,但我真的无法弄清楚。
创建表脚本
CREATE TABLE [dbo].[Utilizadores] (
[Id_Users] INT IDENTITY (1, 1) NOT NULL,
[Username] VARCHAR (50) NOT NULL,
[Password] VARCHAR (50) NOT NULL,
[Role] VARCHAR (50) DEFAULT (user_name()) NOT NULL,
PRIMARY KEY CLUSTERED ([Id_Users] ASC)
);
如果你想获取所有列,可以尝试一下
string querySQL = "SELECT * FROM Utilizadores WHERE Username=@username";
SqlCommand cmd = new SqlCommand(querySQL, conn);
cmd.Parameters.AddWithValue("@username",username);
如果你只想获取Role
列,请尝试此操作
string querySQL = "SELECT Role FROM Utilizadores WHERE Username=@username";
SqlCommand cmd = new SqlCommand(querySQL, conn);
cmd.Parameters.AddWithValue("@username",username);
确保将列的类型设置为
VarChar
否则将无法进行索引查找。docs.microsoft.com/zh-CN/dotnet/api / ... dbdelta.com/addwithvalue-is-evil