数据库连接问题ASP.NET [英] Database connection problem ASP.NET

查看:83
本文介绍了数据库连接问题ASP.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public DBCon()
{
   ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DataCon"].ConnectionString;
}

private void connect()
{
   try
   {
      con = new SqlConnection(ConnectionString);
      if (con.State == ConnectionState.Open)
         con.Close();
      con.Open();
   }
   catch { }
}

public bool ExecuteNonQuery(String sql)
{
   bool Check = false;
   try
   {
      cmd = new SqlCommand();
      cmd.CommandText = sql;
      cmd.CommandType = CommandType.Text;
      connect();
      cmd.Connection = con;
      if (cmd.ExecuteNonQuery() > 0)
         Check = true;
   }
   catch
   {
      Check = false;
   }
   finally
   {
      con.Close();
      cmd.Dispose();
      cmd = null;
   }
   return Check;
}

connectionString="Data Source=amit-pc\\sqlexpress;Initial Catalog=KasturiNaturals;Persist Security Info=True;User ID=sa;Password=123456;"



当我运行此代码时我得到了这个错误。




when i run this code i am getting this error.

ServerVersion = 'con.ServerVersion' threw an exception of type 'System.InvalidOperationException'





我尝试了什么:



i我正在尝试创建方法简化我的代码来访问数据库。



What I have tried:

i am trying to create methods to simplify my code to access database.

推荐答案

你的代码没有意义。您的代码中有一些try-catch块是不必要的,您不必手动关闭和处置连接。只需使用使用语句自动关闭和处理对象即可吃资源,如 SqlConnection SqlCommand 。如果您正在尝试创建一个执行查询命令的方法,那么您可以简单地执行以下操作:



Your code doesn't make sense. There are a few try-catch block in your code which are unnecessary and you don't have to manually close and dispose the connection. Just use the Using statement to automatically closes and disposes object that eat resources such as SqlConnection and SqlCommand. If you are trying to create a method that executes a query command then you can simply do something like this:

private static void ExecuteCommand(string sqlString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        using(SqlCommand command = new SqlCommand(sqlString, connection))
        {
              command.Connection.Open();
              command.ExecuteNonQuery();
        }
    }
}





你可以通过传递你的方法简单地调用ExecuteCommand方法sql语句和连接字符串:





You can just then simply call the ExecuteCommand method by passing your sql statement and connectionstring:

ExecuteCommand("YourSqlStatement","YourConnectionString");







当然,您仍然可以重构代码来调用 ConnectionString 内部因此,每次调用 ExcuteCommand 方法时都不必传递连接字符串值。




Of course, you can still refactor the code to call your ConnectionString internally so you don't have to pass the connection string value everytime you call the ExcuteCommand method.


这篇关于数据库连接问题ASP.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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