C#中实现Sql Server的操作

一、连接数据库步骤

第一步:数据库连接字符串

private string connStr ="Persist Security Info=True;User ID=sa;password=123;Initial Catalog=Report;Data Source=192.168.01.01,1433"

第二步:创建连接

SqlConnection con = new SqlConnection(conStr);
con.Open( );//打开连接

第三步:执行

string strSql = $" Select SoftVer From [SoftInfo] where Id =(SELECT MAX(Id) FROM  [SoftInfo])";
SqlCommand cmd = new SqlCommand( sql , con );
cmd.ExecuteNonQuery();

二、封装具体的方法

2.1 查询

sql:要执行的sql语句 param:传递的参数集合 type:命令类型,如果执行的是存储过程,则需要选择StoredProcedure类型

public static DataTable QueryDB(string sql, List<SqlParameter> param, CommandType type = CommandType.Text)
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(connStr))
    {
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            con.Open();
            if (param != null)
            {
                cmd.Parameters.AddRange(param.ToArray());
            }
            cmd.CommandType = type;
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                da.Fill(dt);
            }
        }
    }
    return dt;
}

调用--非存储过程类型

string strSql = $" Select SoftVer From [SoftInfo] where Id = @Id";//查询字符串
SqlParameter Id = new SqlParameter("@Id",15);//参数
List<SqlParameter> paramList = new List<SqlParameter>( ){ Id };//参数集合
DataTable dt = DBHelper.QueryDB(strSql, paramList);//返回查询结果

调用--存储过程类型 假设存在存储过程getCompletion 并且带有输出参数count

string strSql = $"getCompletion";
SqlParameter count  = new SqlParameter("@count ", SqlDbType.Int);//参数
count.Direction = ParameterDirection.Output;//方向为输出类型
List<SqlParameter> paramList = new List<SqlParameter>( ){ count };//参数集合
DBHelper.QueryDB(strSql, paramList, CommandType.StoredProcedure);
Console.WriteLine(Id.Value);//打印存储过程输出参数的值

2.2 修改 删除 增加

返回受影响的行数,方便判断是否执行成功,调用方法与上面一致

public static int UpdateDB(string sql, List<SqlParameter> param, CommandType type = CommandType.Text)
{
    using (SqlConnection con = new SqlConnection(conStr))
    {
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            con.Open();
            if (param != null)
            {
                cmd.Parameters.AddRange(param.ToArray());
            }
            cmd.CommandType = type;
            return cmd.ExecuteNonQuery();
        }
    }
}

2.3 执行聚合函数

public static object ScalarDB(string sql, List<SqlParameter> param, CommandType type = CommandType.Text)
{
    using (SqlConnection con = new SqlConnection(conStr))
    {
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            con.Open();
            if (param != null)
            {
                cmd.Parameters.AddRange(param.ToArray());
            }
            cmd.CommandType = type;
            object obj = cmd.ExecuteScalar();
            return obj;
        }
    }
}

 

posted @ 2022-11-27 18:27  just--like  阅读(640)  评论(0编辑  收藏  举报