web.config中加入数据库联接字符串

 <connectionStrings>
    
<!--链接SQL Server数据库的链接字符串-->
    
<add name="SQLCONNECTIONSTRING" connectionString="data Source=192.168.1.55;database=db_name;user id=db_user_;pwd=password" providerName="System.Data.SqlClient"></add>
  
</connectionStrings>

 

app_code中  user.cs

using System.Data.SqlClient;


/// <summary>
/// 接口
/// </summary>
public interface IUser
{
    SqlDataReader GetUserLoginByProc(
int p_u_id);
}
/// <summary>
/// user 的摘要说明
/// </summary>
public class User:IUser
{
    
public User()
    {
        
//
        
// TODO: 在此处添加构造函数逻辑
        
//
    }

    
public SqlDataReader GetUserLoginByProc(int p_u_id)
    {
        
///创建链接
        SqlConnection myConnection = new SqlConnection(
            ConfigurationManager.ConnectionStrings[
"SQLCONNECTIONSTRING"].ConnectionString);

        
///创建Command
        SqlCommand myCommand = new SqlCommand("pr_test", myConnection);
        
///设置为执行存储过程
        myCommand.CommandType = CommandType.StoredProcedure;

        
///添加存储过程的参数
        SqlParameter pUID = new SqlParameter("@u_id", SqlDbType.Int);
        pUID.Value 
= p_u_id;
        myCommand.Parameters.Add(pUID);


        
///定义DataReader
        SqlDataReader dr = null;
        
try
        {
            
///打开链接
            myConnection.Open();
            
///读取数据
            dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
        }
        
catch (SqlException ex)
        {
            
///抛出异常
            throw new Exception(ex.Message, ex);
        }
        
///返回DataReader
        return dr;
    }
}

 

 

代码调用

 protected void Page_Load(object sender, EventArgs e)
    {
        IUser user 
= new User();
        SqlDataReader sdr 
= user.GetUserLoginByProc(1);
        
if (sdr.Read())
        {
            Label1.Text 
= sdr["u_truename"].ToString();
        }
        
else
        {
            Label1.Text 
= "xxxxxxxxxxxxxxx";
        }
    }
posted on 2008-08-20 01:21  晃晃悠悠  阅读(554)  评论(0)    收藏  举报