【发布时间】:2021-10-24 10:53:24
【问题描述】:
在 C#.NET Core 5 项目中,我使用 System.Data.SQLClient 4.8.2 连接到 SQL Server 11。
这段代码运行良好。
public List<Contract> ReadDBView(Contract contract)
{
List<Contract> contracts = new List<Contract> { };
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "server01";
builder.UserID = "user1";
builder.Password = "SecretPassword";
builder.InitialCatalog = "archiv1";
String sql = "SELECT name, group_name, group_country_code, FROM[dbo].[GROUPS] where number like '%" + contract.Number.ToString() + "'";
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
contract.DealerName = reader["name"].ToString();
contract.GroupName = reader["group_name"].ToString();
contract.Country = reader["group_country_code"].ToString();
contracts.Add(contract);
}
}
}
connection.Close();
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
return contracts;
}
但过了一会儿它就冻结了——知道如何防止冻结吗?
返回值有时为空。由于我很长时间没有使用 C# 做任何代码提示,非常感谢。
【问题讨论】:
-
我强烈建议您修复代码中的主要安全漏洞; SQL 注入现在应该已经死了。我们更喜欢参数是有原因的。
-
你多久运行一次?你有针对同一张表的任何其他 SQL 语句吗?
-
@Larnu 你能分享一个好例子的链接吗
-
知道SQL Injection很重要。
-
@jgauffin 我会检查,但可能不超过 5000 次
标签: c# sql-server .net-core