我尝试连接数据库时出错

时间:2016-12-21 15:31:00

标签: c# database connection runtime-error

以下是我的代码。我在Openconnection()函数中传递连接字符串的位置。但是当调用Openconnection方法时,我收到错误。

 public class dbconn
    {
        string ConnetionString = null;
        string State = "";
        SqlConnection cnn;
    public string openconnection()
    {
        ConnetionString = @"Data Source=myservername;Initial Catalog=mydbname;Integrated Security=True";
        cnn = new SqlConnection(ConnetionString);
        try
        {
            cnn.Open();
            return State;
        }
        catch (Exception ex)
        {
             ...............
        }
    }

    public string closeconnection()
    {
        ConnetionString = @"Data Source=myservername;Initial Catalog=mydbname;Integrated Security=True";
        cnn = new SqlConnection(ConnetionString);
        try
        {
            cnn.Close();
            return State;
        }
        catch (Exception ex)
        {
           .........
        }
    }



}

当我尝试从我的c#代码部分调用此类时,如

public dbconn dbcon;
private void btnsave_Click(object sender, EventArgs e)
{
  string State="";
  try
  {
    State= dbcon.openconnection();//*** Error in this line
    if (State!= "")
    {
      MessageBox.Show(State, "Lost Connection");
    }
 }
}

在***部分,我遇到了错误。

1 个答案:

答案 0 :(得分:2)

从您的评论中,我说得对。您需要实例化dbconn对象。

dbcon = new dbconn();

总的来说,我建议不要将这种做法用于SQL连接。无论您何时进行任何类型的数据库访问,请查看using。 (正如Tim Schmelter已经在评论中指出的那样)