Webconfig Code
<configuration>
<appSettings>
<add key= "Myconnect" value= "server=.; uid=sa;password= ' 1 ';d atabase=test "/>
</appSettings>
</configuration>
?
Database Class Code
Using System;
Using System.Data;
Using System.Configuration;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;
?
<summary>
Summary description of Db_class
</summary>
public class Db_class
{
SqlConnection myconn;
SqlCommand myCMD;
DataSet ds; Data set
SqlDataAdapter adapt;
???? Public Db_class ()
???? {
???????? //
???????? TODO: Add constructor logic here
???????? //
????}
Public SqlConnection getconnection ()
{
String mystr = configurationmanager.appsettings["Myconnect"]. ToString ();
SqlConnection myconn = new SqlConnection (MYSTR);
return myconn;
}
?
public int Execnonquery (string strSQL)
{
?
Try
{
myconn = getconnection ();//connection to database
myCMD = new SqlCommand ();//Initialize SqlCommand class object
myCMD. Connection = myconn;
Mycmd.commandtext = strSQL;
if (myCMD. Connection.state! = ConnectionState.Open)
{
myCMD. Connection.Open ();//Open a connection to the database
}
int A=mycmd. ExecuteNonQuery ();//Execute SQL operation and return the number of rows affected
return A;
?
}
catch (Exception ex)
{
throw new Exception (ex. Message, ex);
?
}
Finally
{
if (myCMD. Connection.state = = ConnectionState.Open)
{//Disconnect, release resources
myCMD. Connection.close ();
MyConn. Dispose ();
myCMD. Dispose ();
?
}
}
}
?
public string Execscalar (string strSQL)
{
Try
{
myconn = getconnection ();//connection to database
myCMD = new SqlCommand ();//Initialize SqlCommand class object
myCMD. Connection = myconn;
Mycmd.commandtext = strSQL;
if (myCMD. Connection.state! = ConnectionState.Open)
{
myCMD. Connection.Open ();//Open a connection to the database
}
Returns the value of the first column of the first row using the ExecuteScalar method of the SqlCommand object
strSQL = Convert.ToString (mycmd. ExecuteScalar ());
string another = Convert.ToString (mycmd. ExecuteScalar ());
return another;
}
catch (Exception ex)
{
throw new Exception (ex. Message, ex);
?
}
Finally
{
if (myCMD. Connection.state = = ConnectionState.Open)
{//Disconnect, release resources
MyConn. Dispose ();
myCMD. Connection.close ();
myCMD. Dispose ();
?
}
}
}
?
Public DataTable GetDataSet (string strSQL, String TableName)
{
ds = new DataSet ();
Try
{
myconn = getconnection ();//connection to database
adapt = new SqlDataAdapter (strSQL, myconn); Instantiating a SqlDataAdapter class object
Adapt. Fill (ds, TableName);//Fill data set
Return DS. tables[tablename];//A collection of tables that return dataset datasets
?
}
catch (Exception ex)
{
throw new Exception (ex. Message, ex);
?
}
Finally
{//Disconnect, release resources
MyConn. Close ();
Adapt. Dispose ();
Ds. Dispose ();
MyConn. Dispose ();
}
?
}
}
. net/c# connecting to SQL Server