SqlServer的那些常用操作(一)

來源:互聯網
上載者:User

一、判斷資料庫的串連狀態:
(1)Using方法:
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (SqlConnection connection = new SqlConnection(""))
        {
            connection.Open();
            if (connection.State == ConnectionState.Open)
            {
                //已經開啟
            }
        }
    }
}

(2)“Try{}  Catch{}”方法
try
{
SqlConnection conn = new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;");
  conn.Open();
}
catch
{
//串連失敗
}

(3)永遠返回正確的資料連線

  private SqlConnection connection;
  public SqlConnection Connection
  {
  get
  {
  string connectionString = "server=.;database=DB;uid=SA;pwd=123456";
  if (connection == null)
  {
  connection = new SqlConnection(connectionString);
  connection.Open();//這裡就是開啟了,說明串連上了
  }
  else if (connection.State == System.Data.ConnectionState.Closed)
  {
  connection.Open(); //這裡就是開啟了,說明串連上了
  }
  else if (connection.State == System.Data.ConnectionState.Broken)
  {
  connection.Close();
  connection.Open();//這裡就是開啟了,說明串連上了
  }
  return connection; //不管什麼情況,這裡總是返回一個開啟的串連
  }
  }

二、返回本機電腦的所有資料庫名稱
USE master
SELECT dbid, DB_NAME(dbid) AS DB_NAME
FROM sysdatabases
ORDER BY dbid
GO

三、返回指定資料庫中所有的表名稱
SELECT name FROM sys.sysobjects WHERE type='U'

四、返回指定表中的所有欄位
SELECT *  FROM syscolumns  WHERE id in( SELECT id  FROM sysobjects   WHERE (name = '" + tbname + "'))

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.