public class users
{
public string id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public string country { get; set; }
}
public class IDaccesscontrol
{
public static List<users> GetAllEmployees()
{
List<users> listEmployees = new List<users>();
string CS = ConfigurationManager.ConnectionStrings["User_KarlConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select from user_karl", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
users users = new users();
users.id = rdr["id"].ToString();
users.username = rdr["username"].ToString();
users.password = rdr["password"].ToString();
users.email = rdr["email"].ToString();
users.country = rdr["country"].ToString();
listEmployees.Add(users);
con.Close();
}
}
return listEmployees;
}
}
}
答案 0 :(得分:2)
尝试select * from user_karl
。
您只是在SQL语句本身中出现语法错误。 C#无法在编译时选择它,因此您将获得运行时异常。
如果您无法找到这些语法错误,有时它可以帮助将SQL语句复制/粘贴到SQL Server Management Studio并看到它告诉您那里。要获取应用程序发送到服务器的确切语句,请使用SQL事件探查器(SQL Server Management Studio中的“工具”菜单)。
答案 1 :(得分:0)
正确的语法是从user_karl 中选择*。在上面的代码中,您错过了星号。它检索表格中的整个数据“user_karl”
在代码中更改此行:
SqlCommand cmd = new SqlCommand("Select * from user_karl", con);
答案 2 :(得分:-1)
Your code have some errors, not only sql-query. Change your code to the following:
public class users
{
public string id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public string country { get; set; }
}
public class IDaccesscontrol
{
public static List<users> GetAllEmployees()
{
List<users> listEmployees = new List<users>();
string CS = ConfigurationManager.ConnectionStrings["User_KarlConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("Select * from user_karl", con); //when selecting something from a database, you have to appoint exactly what you want to eject
//otherwise if will occur an error as you had. * means we want to eject all columns from the table
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
users users = new users();
users.id = rdr["id"].ToString();
users.username = rdr["username"].ToString();
users.password = rdr["password"].ToString();
users.email = rdr["email"].ToString();
users.country = rdr["country"].ToString();
listEmployees.Add(users);
//con.Close(); you are in the while loop, so you can't close connection until you will not finish your work with data
}
con.Close(); //working with your reader has been finished, so we can close connection
}
return listEmployees;
}
}