Copy codeThe Code is as follows:
Using System;
Using System. Data;
Using System. Data. SqlClient;
Public class Helper
{
Public static void Main ()
{
// Connection string
String strcon = "server =.; database = blog; uid = sa; pwd = 1 ";
SqlHelper helper = new SqlHelper (strcon );
// The employee table contains the neme (varchar (20), age (int), and sex (bit) fields;
String SQL = "select * from employee ";
SqlDataReader reader = helper. Reader (SQL, null );
Using (reader)
{
While (reader. Read ())
{
Console. WriteLine (reader ["name"]. ToString ());
}
}
/* String SQL = "insert into employee values (@ name, @ age, @ sex )";
SqlParameter [] ps = new SqlParameter []
{
New SqlParameter ("@ name", SqlDbType. VarChar, 20 ),
New SqlParameter ("@ age", SqlDbType. Int ),
New SqlParameter ("@ sex", SqlDbType. Int)
};
Ps [0]. Value = "Zhang Yu ";
Ps [1]. Value = 40;
Ps [2]. Value = 1;
Helper. ExecuteNonQuery (SQL, ps );*/
}
}
Public class SqlHelper
{
Private SqlConnection con = null;
Private SqlCommand cmd = null;
Public SqlHelper (string strcon)
{
Con = new SqlConnection (strcon );
Cmd = new SqlCommand ();
Cmd. Connection = con;
}
// Execute the initialization Command object
Private void PreparedCommand (string SQL, params SqlParameter [] param)
{
Cmd. CommandText = SQL;
// Clear the objects in Parameteras
Cmd. Parameters. Clear ();
If (param! = Null)
{
Foreach (SqlParameter p in param)
{
Cmd. Parameters. Add (p );
}
}
Con. Open ();
}
/* Execute non-query statements */
// Parameters
Public int ExecuteNonQuery (string SQL, params SqlParameter [] param)
{
PreparedCommand (SQL, param );
Int I = cmd. ExecuteNonQuery ();
Close ();
Return I;
}
// No Parameters
Public int ExecuteNonQuery (string SQL)
{
PreparedCommand (SQL, null );
Int I = cmd. ExecuteNonQuery ();
Close ();
Return I;
}
/* Execute the query statement */
// Parameters
Public SqlDataReader Reader (string SQL, params SqlParameter [] param)
{
PreparedCommand (SQL, param );
Return cmd. ExecuteReader ();
}
// No Parameters
Public SqlDataReader Reader (string SQL)
{
PreparedCommand (SQL, null );
Return cmd. ExecuteReader ();
}
Public void Open ()
{
Con. Open ();
}
Public void Close ()
{
Cmd. Dispose ();
Con. Close ();
}
}