如何保持连接数据库直到屏幕关闭? [英] How to stay connected to database until screen close?

查看:73
本文介绍了如何保持连接数据库直到屏幕关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为Windows-CE平台开发了一个C#程序.该程序为每个单独的交互打开和关闭与数据库的连接.请参见下面的代码.

I developed a C# program for Windows-CE platform. The program open and close the connection to the database for every single interaction. See the code below.

按钮单击:

private void btnStkIn_Click(object sender, EventArgs e)
{
    formStockIn = new frmStkIn();
    formStockIn.Show();
}

选择数据:

try
{
    using (SqlConnection sqlConn = new SqlConnection(<connection-string>))
    {
        sqlConn.Open();
        //Execute command
        SqlCommand sqlCmd = new SqlCommand(<Select Query>, sqlConn);
        SqlDataReader sqlReader = sqlCmd.ExecuteReader();

        while (sqlReader.Read())
        {
            <Statement here>
        }
    }
}
catch
{
    //SQL command error
    itemDT.ErrorMessage = "Select process is failed.Please contact system admin.";
    itemDT.Result = 12;
}

更新数据:

try
{
    using (SqlConnection sqlConn = new SqlConnection(<connection-string>))
    {
        sqlConn.Open();
        //Execute command
        SqlCommand sqlCmd = new SqlCommand(<Update Query>, sqlConn);
        if (sqlCmd.ExecuteNonQuery() <= 0)
        {
            //No row affect
            return -99;
        }
        else
        {
            //Completed
            return 0;
        }
    }
}
catch
{
    //Sql command error
    return 99;
}

我想一次连接数据库(当显示表格时),然后选择使用相同的连接进行插入,更新数据,并在关闭屏幕时关闭连接.在运行时,某些屏幕可以选择多次更新.

I would like to connect to database once (when the form in shown) and then do select, Insert, Update the data using the same connection and close the connection when I close the screen. At run-time, some screen can select-update more than once.

我该怎么办?

推荐答案

您正在做什么.优良作法是在尽可能短的时间内保持连接打开,然后再进行处理.这就是您正在做的事,这很好.

What you are doing is fine. It is good practice to keep the connection open for the shortest time possible and then disposing it. This is what you are doing and that's good.

如果您将其保持打开状态,并且用户在午餐或休假时没有其他任何点击,则表明您没有充分理由保持连接.

If you keep it open and the user goes off on lunch or vacation and clicks nothing else, you are keeping a connection for no good reason.

如果需要同时执行多项操作,请打开一个连接并执行查询,然后立即关闭连接.

If you need to do multiple things at the same time, then open one connection and execute the queries and then close the connection right away.

这篇关于如何保持连接数据库直到屏幕关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆