我正在制作一个学校项目所需的 Web api 服务器,因为我们必须在不同平台上创建多个应用程序以通过消息进行通信,并且 Web api 服务器具有 GET、POST 和 DELETE 方法。
现在我有一个 GET 方法,它将使用 ID 返回表中的一行(例如 http://localhost:1442/api/Users/1 将返回 ID 为 1 的用户)
代码如下所示:
public User Get(int id)
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Downloads\SERVER\SERVER\App_Data\dbCoffeeBreak_.mdf;Integrated Security=True";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from tbUsers where ID=" + id + "";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
User u = null;
while (reader.Read())
{
u = new User();
u.ID = Convert.ToInt32(reader.GetValue(0));
u.Login = reader.GetValue(1).ToString();
u.Password = reader.GetValue(2).ToString();
u.Avatar = reader.GetValue(3).ToString();
u.Email = reader.GetValue(4).ToString();
u.Online = Convert.ToBoolean(reader.GetValue(5));
}
myConnection.Close();
return u;
}
但我不知道如何做到这一点,例如仅输入 http://localhost:1442/api/Users服务器将返回表中的所有列。我尝试将 sqlCmd.CommandText = 设置为仅 Select * from tbUsers
但这仅返回表中的最后一个用户,而不是全部。
最佳答案
那是因为您只返回来自 Reader.Read
的最后一个用户
有几个问题和建议给您
1. Make
Id
as optional parameter , so that if you dont pass any
Id, it will query for all
users`. With this you dont need to create separate method for getting all users.2. Return
List<User>
instead of return singleUser
public List<User> Get(int? id = null)
{
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Downloads\SERVER\SERVER\App_Data\dbCoffeeBreak_.mdf;Integrated Security=True";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
if(id !=null)
sqlCmd.CommandText = "Select * from tbUsers where ID=" + id + "";
else
sqlCmd.CommandText = "Select * from tbUsers ";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
List<User> users = List<User>();
while (reader.Read())
{
u = new User();
u.ID = Convert.ToInt32(reader.GetValue(0));
u.Login = reader.GetValue(1).ToString();
u.Password = reader.GetValue(2).ToString();
u.Avatar = reader.GetValue(3).ToString();
u.Email = reader.GetValue(4).ToString();
u.Online = Convert.ToBoolean(reader.GetValue(5));
users.Add(u);
}
myConnection.Close();
return users;
}
Plus always use Parameterized queries to prevent SQL Injection Attacks
建议您将查询更新为
sqlCmd.CommandText = "Select * from tbUsers where ID=@Id";
sqlCmd.Parameters.AddWithValue("@Id", id);
关于C# ASP.NET Web Api Controller - 使用 SqlCommand 从表中获取所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48250755/