C#调用存储过程

1、调用无返回值的存储过程
--存储过程
create proc myinsert
@username varchar(10),
@password varchar(10),
@name varchar(10),
@usertype varchar(10),
@createpeople varchar(10)
as
    insert into SystemUsers(UserName,PassWord,Name,UserType,CreatPeople)values(@username,@password,@name,@usertype,@createpeople)
go

--C#代码
string strsql = "Data Source=192.168.24.53;Initial Catalog=JF_Charging_System;Persist Security Info=True;User ID=sa;Password=1";//数据库链接字符串
string sql = "myinsert";//要调用的存储过程名
SqlConnection conStr = new SqlConnection(strsql);//SQL数据库连接对象,以数据库链接字符串为参数
SqlCommand comStr = new SqlCommand(sql, conStr);//SQL语句执行对象,第一个参数是要执行的语句,第二个是数据库连接对象
comStr.CommandType = CommandType.StoredProcedure;//因为要使用的是存储过程,所以设置执行类型为存储过程
//依次设定存储过程的参数
comStr.Parameters.Add("@username", SqlDbType.VarChar, 10).Value = "11";
comStr.Parameters.Add("@password", SqlDbType.VarChar, 10).Value = "11";
comStr.Parameters.Add("@name", SqlDbType.VarChar, 10).Value = "11";
comStr.Parameters.Add("@usertype", SqlDbType.VarChar, 10).Value = "11";
comStr.Parameters.Add("@createpeople", SqlDbType.VarChar, 10).Value = "11";
conStr.Open();//打开数据库连接
MessageBox.Show(comStr.ExecuteNonQuery().ToString());//执行存储过程
conStr.Close();//关闭连接

2、调用有返回值或结果集的存储过程
--存储过程
CREATE PROC P_TEST
@Name VARCHAR(20),
@Rowcount INT OUTPUT
AS
BEGIN
    SELECT * FROM T_Customer WHERE NAME=@Name
    SET @Rowcount=@@ROWCOUNT
END
GO

--C#代码
String DBConnStr = "Data Source=192.168.24.53;Initial Catalog=JF_Charging_System;Persist Security Info=True;User ID=sa;Password=1";//数据库链接字符串
DataSet MyDataSet=new DataSet();
System.Data.SqlClient.SqlDataAdapter DataAdapter=new System.Data.SqlClient.SqlDataAdapter();
System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(DBConnStr);
if (myConnection.State!=ConnectionState.Open)
{
    myConnection.Open();
}
System.Data.SqlClient.SqlCommand myCommand = new System.Data.SqlClient.SqlCommand("P_Test",myConnection);
myCommand.CommandType=CommandType.StoredProcedure;
//添加输入查询参数、赋予值
myCommand.Parameters.Add("@Name",SqlDbType.VarChar);
myCommand.Parameters["@Name"].Value ="A";

//添加输出参数
myCommand.Parameters.Add("@Rowcount",SqlDbType.Int);
myCommand.Parameters["@Rowcount"].Direction=ParameterDirection.Output;

myCommand.ExecuteNonQuery();
DataAdapter.SelectCommand = myCommand;
if (MyDataSet!=null)
{
    DataAdapter.Fill(MyDataSet,"table");
}
string Rowcount = myCommand.Parameters["@Rowcount"].Value.ToString();
if (myConnection.State == ConnectionState.Open)
{
    myConnection.Close();
}

3、几个常用的方法

/// <summary>
/// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
    SqlConnection connection = new SqlConnection(connectionString);
    SqlDataReader returnReader;
    connection.Open();
    SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
    command.CommandType = CommandType.StoredProcedure;
    returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
    return returnReader;
}

/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        DataSet dataSet = new DataSet();
        connection.Open();
        SqlDataAdapter sqlDA = new SqlDataAdapter();
        sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
        sqlDA.Fill(dataSet, tableName);
        connection.Close();
        return dataSet;
    }
}


public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        DataSet dataSet = new DataSet();
        connection.Open();
        SqlDataAdapter sqlDA = new SqlDataAdapter();
        sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
        sqlDA.SelectCommand.CommandTimeout = Times;
        sqlDA.Fill(dataSet, tableName);
        connection.Close();
        return dataSet;
    }
}


/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
    SqlCommand command = new SqlCommand(storedProcName, connection);
    command.CommandType = CommandType.StoredProcedure;
    foreach (SqlParameter parameter in parameters)
    {
        if (parameter != null)
        {
            // 检查未分配值的输出参数,将其分配以DBNull.Value.
            if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&(parameter.Value == null))
            {
                parameter.Value = DBNull.Value;
            }
            command.Parameters.Add(parameter);
        }
    }

    return command;
}

/// <summary>
/// 执行存储过程,返回Output输出参数值
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>object</returns>
public static object RunProcedure(string storedProcName, IDataParameter[] paramenters)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = BuildQueryCommand(connection, storedProcName, paramenters);
        command.ExecuteNonQuery();
        object obj=command.Parameters["@Output_Value"].Value; //@Output_Value和具体的存储过程参数对应
        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
        {
            return null;
        }
        else
        {
            return obj;
        }
    }
}

/// <summary>
/// 执行存储过程,返回影响的行数
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="rowsAffected">影响的行数</param>
/// <returns></returns>
public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        int result;
        connection.Open();
        SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
        rowsAffected = command.ExecuteNonQuery();
        result = (int)command.Parameters["ReturnValue"].Value;
        return result;
    }
}

/// <summary>
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand 对象实例</returns>
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
    SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
    command.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
    return command;
}

posted on 2016-05-05 17:09  淹死的鸭子  阅读(517)  评论(0编辑  收藏  举报

导航