Common SQL server operations (1)

Source: Internet
Author: User

1. Determine the database connection status:
(1) Using Method:
Public partial class _ default: system. web. UI. page
{< br> protected void page_load (Object sender, eventargs e)
{< br> using (sqlconnection connection = new sqlconnection (""))
{< br> connection. open ();
If (connection. state = connectionstate. open)
{< br> // already opened
}< BR >}

(2) "try {} catch {}" Method
Try
{
Sqlconnection conn = new sqlconnection ("Data Source = myserveraddress; initial catalog = mydatabase; user id = myusername; Password = mypassword ;");
Conn. open ();
}
Catch
{
// Connection failed
}

(3) always return the correct data connection

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 (); // This indicates that connection is enabled.
}
Else if (connection. State = system. Data. connectionstate. Closed)
{
Connection. open (); // This indicates that connection is enabled.
}
Else if (connection. State = system. Data. connectionstate. Broken)
{
Connection. Close ();
Connection. open (); // This indicates that connection is enabled.
}
Return connection; // in any case, an open connection is always returned.
}
}

2. Return the names of all databases on the local computer.
Use master
Select dbid, db_name (dbid) as db_name
From sysdatabases
Order by dbid
Go

3. Return the names of all tables in the specified database.
Select name from SYS. sysobjects where type = 'U'

4. Return all fields in the specified table
select * From syscolumns where ID in (select ID from sysobjects where (name = '"+ tbname + "'))

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.