一、判断数据库的连接状态:
(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 + "'))