private static string connString = "server=.;database=hotel;uid=aa;pwd=123";//最好從配置文件中取出sql
public static SqlConnection conn = new SqlConnection(connString);ide
在配置文件中進行配置並取出ui
<?xml version="1.0" encoding="utf-8"?>.net
<configuration>server
<configuration>xml
<connectionStrings>utf-8
<add name="Test"string
connectionString="Data Source=.;Initial Catalog=HospitalInstrument;User ID=sa;Password=123"it
providerName="System.Data.SqlClient"/>io
</connectionStrings>
</configuration>
添加引用System.Configuration
使用該命名空間下的ConfigrationManager類
string constr=ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
//公用的增刪改方法
public static bool ZhengShanGai(string sql)
{
bool flag = false;
SqlCommand com = null;
try
{
if (sql == null || sql == "")
{
return false;
}
if (conn.State != ConnectionState.Open)
conn.Open();
com = new SqlCommand(sql, conn);
if (com.ExecuteNonQuery() > 0)
flag = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
com.Dispose();
conn.Close();
}
return flag;
}
//公用的查詢方法 ,返回值爲SqlDateReader
public static SqlDataReader Query(string sql)
{
SqlCommand com = null;
SqlDataReader reader = null;
try
{
if (sql == null || sql == "")
{
return null;
}
if (conn.State != ConnectionState.Open)
conn.Open();
com = new SqlCommand(sql, conn);
//當關閉reader後鏈接自動關閉
reader = com.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
return null;
throw ex;
}
return reader;
}
//公用的查詢方法 ,返回值爲DataTable;
public static DataTable QueryInfo(string sql)
{
DataTable dt = new DataTable();
SqlDataAdapter da = null;
try
{
DBHelper.conn.Open();
da = new SqlDataAdapter(sql, DBHelper.conn);
da.Fill(dt);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
DBHelper.conn.Close();
}
return dt;
}
// 執行帶參數存儲過程的方法
public bool ExcuteProc(string procName, SqlParameter[] procParams)
{
bool flag = false;
SqlCommand com = null;
try
{
if (procName == null || procName == "") return false;
if (conn.State != ConnectionState.Open) conn.Open();
com = new SqlCommand(procName, conn);
com.CommandType = CommandType.StoredProcedure;
if (procParams != null)
{
foreach (SqlParameter procParam in procParams)
{
com.Parameters.Add(procParam);
}
}
if (com.ExecuteNonQuery() > 0) flag = true;
}
catch (Exception)
{
return false;
}
finally
{
com.Dispose();
conn.Close();
}
return flag;
}
}
以上是很簡單的ado.net基礎幫助類,若有什麼疑問,或是認爲我寫的有錯,我願意和你們交流