Đây là lớp CMyConnection của mình làm trong bài đồ án môn học CNPM nó chạy tốt đối với server là localhost hay là 1 IP nào khác.
Bạn tham khảo nhé
PHP Code:
public class CMyConnection
{
private string sCon="";
private SqlConnection con;
private string sDatabase="";
private string strError="";
private string sIP = "";
private string sUserName;
private string sPassword;
private CMyFile fFile;
public CMyFile File
{
set { fFile = value; }
get { return fFile; }
}
public string IP
{
set { sIP = value; }
get { return sIP; }
}
public string UserName
{
set { sUserName = value; }
get { return sUserName; }
}
public string Password
{
set { sPassword = value; }
get { return sPassword; }
}
public string ConnectionString
{
set{sCon = value;}
get { return sCon; }
}
public SqlConnection sqlCon
{
set { con = value; }
get { return con; }
}
public string DatabasePath
{
set { sDatabase = value; }
get { return sDatabase; }
}
public string Error
{
set { strError = value; }
get { return strError; }
}
public CMyConnection()
{
con = new SqlConnection();
sCon = "Data Source =.; Integrated Security=SSPI;Initial Catalog=DayNauAn";
fFile = new CMyFile();
}
public CMyConnection(string DatabaseName,string ServerName, string UserName, string Password)
{
sDatabase = DatabaseName;
sIP = ServerName;
sUserName = UserName;
sPassword = Password;
con = new SqlConnection();
fFile = new CMyFile();
}
public string BuildConnectionString()
{
string sResult = "";
//neu khong co ip thi mac dinh la localhost
if (sIP == "")
{
sResult += "Data Source=.";
}
else
{
sResult += "Data Source=" + sIP;
}
sResult += "; Initial Catalog= " + sDatabase + ";";
if(sUserName != "")
{
sResult += "User Id = " + sUserName + "; Password = " + sPassword + ";";
}
return sResult;
}
public bool Connection()
{
bool bResult;
sCon = BuildConnectionString();
try
{
if (con.State == System.Data.ConnectionState.Closed)
{
con.ConnectionString = sCon;
con.Open();
}
bResult = true;
}
catch
{
bResult = false;
}
return bResult;
}
public bool Connection(string sUser, string sPass)
{
bool bResult;
sCon = "DataSource=.; Initial Catalog=" + sDatabase;
sCon += ";user ID=" + sUser + ";Password=" + sPass;
try
{
con.ConnectionString = sCon;
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
bResult = true;
}
catch
{
bResult = false;
}
return bResult;
}
public bool Connection(bool toSqlExpress)
{
bool bResult = toSqlExpress;
if (toSqlExpress == true)
{
sCon = "Data Source=.\\SQLEXPRESS;AttachDbFilename='" + sDatabase;
sCon += "';Integrated Security=True;Connect Timeout=30;User Instance=False";
try
{
con.ConnectionString = sCon;
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
bResult = true;
}
catch(Exception e)
{
bResult = false;
strError = e.Message;
}
}
return bResult;
}
public void Disconnection()
{
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}
}