1. 程式人生 > 其它 >SqlServer資料庫連線類

SqlServer資料庫連線類

namespace VT301
{
class SqlConnectClass
{
public struct sqlInf
{
public string ServerName;
public string UserID;
public string PWD;
public string DATABase;
public string command;
public string tableName;
}

public sqlInf sql;

private void SQLInfConnect()
{
string[] str = File.ReadAllLines("SQL.txt", Encoding.Default);
char[] sp = { ':' };
for (int i = 0; i < str.Length; i++)
{
string[] str2 = str[i].Split(sp, StringSplitOptions.RemoveEmptyEntries);
if (str2[0] == "ServerName")
{
sql.ServerName = str2[1];
}
else if (str2[0] == "UserID")
{
sql.UserID = str2[1];
}
else if (str2[0] == "PWD")
{
sql.PWD = str2[1];
}
else if (str2[0] == "DataBase")
{
sql.DATABase = str2[1];
}
//(SQL.DATABase, SQL.PWD, SQL.ServerName, SQL.UserID);
}

}

public void Connect()
{
SQLInfConnect();
sql.command = "";
sql.tableName = "";
}

SqlConnection sqlcon;

public SqlConnection SqlConnect()
{
String stringInf = "Data source=" + sql.ServerName + ";Database=" + sql.DATABase + ";User id=" + sql.UserID + ";PWD=" + sql.PWD + ";Connect Timeout=1";
sqlcon = new SqlConnection(stringInf);
sqlcon.Open();
return sqlcon;
}

public void SQLClose()
{
if (sqlcon.State == System.Data.ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}

public SqlDataReader GetSqlData()
{
SqlConnect();
SqlCommand comm = new SqlCommand(sql.command, sqlcon);
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
SqlDataReader sqlRead = comm.ExecuteReader();
comm.Dispose();
SQLClose();
return sqlRead;

}

public void ChangeData()
{
SqlConnect();
SqlCommand comm = new SqlCommand(sql.command, sqlcon);
if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
comm.ExecuteNonQuery();
comm.Dispose();
SQLClose();
}
}
}