的步骤如下:
<connectionStrings>
<add name="MyDBConnectionString" connectionString="Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUserName;Password=YourPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>
替换"YourServerName"、"YourDatabaseName"、"YourUserName"和"YourPassword"为你的实际数据库信息。
using System.Data.SqlClient;
public class DataAccess
{
private readonly string connectionString;
public DataAccess()
{
connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
}
public void ExecuteQuery(string query)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
}
public SqlDataReader ExecuteReader(string query)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
return command.ExecuteReader();
}
}
public class MyDataController : ApiController
{
private readonly DataAccess dataAccess;
public MyDataController()
{
dataAccess = new DataAccess();
}
public IHttpActionResult Get()
{
string query = "SELECT * FROM MyTable";
SqlDataReader reader = dataAccess.ExecuteReader(query);
// 处理查询结果...
return Ok(result);
}
// 其他操作方法...
}
以上就是使用.NET框架4.7.2 Web API 2.0连接到SQL Server,而不使用实体框架的基本步骤。在实际开发中,你可以根据具体需求进一步扩展和优化代码,并结合其他技术和工具来实现更复杂的功能。
领取专属 10元无门槛券
手把手带您无忧上云