復制代碼 代碼如下:
using System;
using System.Data;
using System.Data.SqlClient;
public class Helper
{
public static void Main()
{
//連接字符串
string strcon = "server = .;database = blog;uid = sa;pwd = 1";
SqlHelper helper = new SqlHelper(strcon);
//表employee中有neme(varchar(20)),age(int),sex(bit)三個字段;
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 = "張宇";
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;
}
//執行初始化Command對象
private void PreparedCommand(string sql,params SqlParameter[]param)
{
cmd.CommandText = sql;
//清空Parameteras中的對象
cmd.Parameters.Clear();
if (param!=null)
{
foreach (SqlParameter p in param)
{
cmd.Parameters.Add(p);
}
}
con.Open();
}
/*執行非查詢語句*/
//有參數
public int ExecuteNonQuery(string sql,params SqlParameter[] param)
{
PreparedCommand(sql,param);
int i = cmd.ExecuteNonQuery();
Close();
return i;
}
//無參數
public int ExecuteNonQuery(string sql)
{
PreparedCommand(sql,null);
int i = cmd.ExecuteNonQuery();
Close();
return i;
}
/*執行查詢語句*/
//有參數
public SqlDataReader Reader(string sql,params SqlParameter[] param)
{
PreparedCommand(sql,param);
return cmd.ExecuteReader();
}
//無參數
public SqlDataReader Reader(string sql)
{
PreparedCommand(sql,null);
return cmd.ExecuteReader();
}
public void Open()
{
con.Open();
}
public void Close()
{
cmd.Dispose();
con.Close();
}
}