ado.net操作数据库的别样用法

发布时间:2019-12-04编辑:脚本学堂
ado.net操作数据库的别样用法,更方便,更好用,有兴趣的朋友可以参考下。

ado.net操作数据库的别样用法,更方便,更好用,有兴趣的朋友可以参考下。

复制代码 代码示例:

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 = "zhangyu";
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();
}
}