gpt4 book ai didi

c# - 在以下情况下使用静态方法访问数据库是否安全

转载 作者:行者123 更新时间:2023-11-29 04:24:11 25 4
gpt4 key购买 nike

我正在将一个 asp 网站升级到 asp.net。我正在尝试采用多种方法。我的基本 dal 层如下,它返回一个数据表并插入一个给定的查询。

using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

public class mydatautility
{
public mydatautility()
{
}
public static DataTable Table(string query)
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
DataTable table = new DataTable();
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Close();
MySqlCommand com = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(com);
con.Open();
da.Fill(table);
con.Close();
da = null;
com = null;
con.Dispose();
}
}
catch (Exception)
{
}
return table;
}
public static int Insert_intoemployee(string query)
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
int done = 0;
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
MySqlCommand com = new MySqlCommand(query, con);
con.Open();
done = com.ExecuteNonQuery();
con.Close();
com = null;
con.Dispose();
}
}
catch (Exception)
{
}
return done;
}
}

我不确定运行 2 个并发查询时会发生什么。
我如何测试并发问题?

最佳答案

不会有并发问题,因为每个请求都有自己的线程,静态方法对每个线程都有单独的调用堆栈。但是,代码中有一些建议。

using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;

public static class mydatautility//change to Utilities
{
public mydatautility()//not required in this scenario
{
}
public static DataTable Table(string query) //change method name to GetTable
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
DataTable table = new DataTable();
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Close();//not required
using(MySqlCommand com = new MySqlCommand(query, con))
{
MySqlDataAdapter da = new MySqlDataAdapter(com);
con.Open();
da.Fill(table);
con.Close();
da = null;// reduntant, not required
com = null;// reduntant, not required
con.Dispose();// reduntant, not required
}
}
}
catch (Exception)
{
}
return table;
}
public static bool InsertEmployee(string query)// consider changing int to bool since you only require result of operation
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
int done = 0;
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
Using(MySqlCommand com = new MySqlCommand(query, con))
{
con.Open();
done = com.ExecuteNonQuery();
con.Close();
com = null;// reduntant, not required
con.Dispose();// reduntant, not required
}
}
}
catch (Exception)
{
}
return done > 0; // checks rows affected greater than 0
}
}

关于c# - 在以下情况下使用静态方法访问数据库是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15216134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com