同时从网络上的多台机器访问托管在一台服务器上的ASP.net应用程序
本文关键字:一台 应用程序 net 服务器 ASP 网络 机器 访问 | 更新日期: 2023-09-27 18:11:52
我为我的学院设计了一个投票应用程序(学生将投票给他们的部门老师)。我已经在服务器上托管了这个网站,从网络上的其他机器访问这个网站没有问题。但是,当有人正在访问数据库表(用于投票的教师表),同时其他人试图从另一台机器访问同一表时,问题就出现了。假设第一个用户投票给2号老师。同时,第二个用户完成投票老师1,当他试图通过点击下一步得到第二个老师。但是系统返回第三个老师等等。
我该怎么做才能解决这个问题?
voting.aspx.cs页面的编码
public partial class voting : System.Web.UI.Page
{
MySqlConnection con = new MySqlConnection("Data Source=localhost; Database=dkd; User Id=root; Password=;");
static string tid;
static int i;
protected void Page_Load(object sender, EventArgs e)
{
Session["dept"] = "Physics";
if (!IsPostBack)
{
i = 2;
loadTeacher(i);
}
}
void loadTeacher(int x)
{
MySqlDataAdapter da = new MySqlDataAdapter("Select * from teachers where department='" + Session["dept"].ToString() + "' order by tid asc", con);
DataSet ds = new DataSet();
da.Fill(ds);
int n=ds.Tables[0].Rows.Count;
//if (n == 0)
//{
// x++;
// loadTeacher(x);
//}
if (x >= n)
{
return;
}
if (n > 0)
{
tid = ds.Tables[0].Rows[x].ItemArray[0].ToString();
lbtid.Text = ds.Tables[0].Rows[x].ItemArray[0].ToString();
lbname.Text = ds.Tables[0].Rows[x].ItemArray[1].ToString();
lbdept.Text = ds.Tables[0].Rows[x].ItemArray[2].ToString();
lbage.Text = ds.Tables[0].Rows[x].ItemArray[3].ToString();
lbsex.Text = ds.Tables[0].Rows[x].ItemArray[4].ToString();
Image1.ImageUrl = "~/Photos/" + ds.Tables[0].Rows[x].ItemArray[5].ToString();
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
con.Open();
MySqlCommand com = new MySqlCommand("insert into rating values(null,'" + lbtid.Text + "','" + lbdept.Text + "','" + ddq1.Text + "','" + ddq2.Text + "','" + ddq3.Text + "','" + ddq4.Text + "','" + ddq5.Text + "','" + ddq6.Text + "','" + ddq7.Text + "','" + ddq8.Text + "','" + ddq9.Text + "','" + ddq10.Text + "')", con);
com.ExecuteNonQuery();
int score;
score = Int32.Parse(ddq1.Text) + Int32.Parse(ddq2.Text) + Int32.Parse(ddq3.Text) + Int32.Parse(ddq4.Text) + Int32.Parse(ddq5.Text) + Int32.Parse(ddq6.Text) + Int32.Parse(ddq7.Text) + Int32.Parse(ddq8.Text) + Int32.Parse(ddq9.Text) + Int32.Parse(ddq10.Text);
MySqlDataAdapter da = new MySqlDataAdapter("Select total from score where teacherid='" + lbtid.Text + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
int tot = Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[0]);
tot = tot + score;
MySqlCommand com1 = new MySqlCommand("Update score set total='" + tot + "' where teacherid ='" + lbtid.Text + "'", con);
com1.ExecuteNonQuery();
con.Close();
clearfields();
i++;
loadTeacher(i);
}
}
保存"当前教师索引"的恰当命名的static int i
是静态的,或者在同一AppDomain中的所有访问者之间共享。
将静态字段更改为如下内容:
private int? _teacherIndex;
protected int TeacherIndex
{
get
{
if (!_teacherIndex.HasValue)
{
var iObject = Session["_teacherIndex"];
var i = 0;
if (iObject != null)
{
int.TryParse(iObject.ToString(), out i);
}
_teacherIndex = i;
}
return _teacherIndex.Value;
}
set { Session["_teacherIndex"] = value; }
}