当前位置:Gxlcms > asp.net > 更方便快捷的外部操作数据库的方法(另类玩法)

更方便快捷的外部操作数据库的方法(另类玩法)

时间:2021-07-01 10:21:17 帮助过:47人阅读

代码如下:

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

}

人气教程排行