连接数据库如何封装?
连接字符转已经写到web.config文件中
<?xml version= "1.0 " encoding= "utf-8 "?>
<configuration>
<appSettings/>
<connectionStrings>
<add name= "ConnectionString " connectionString= "Data Source=250;Persist Security Info=True;User ID=chenyi;Password=123456;Unicode=True "
providerName= "System.Data.OracleClient " />
</connectionStrings>
<system.web>
<compilation debug= "false " />
<authentication mode= "Windows " />
</system.web>
</configuration>
连接的类该怎么写?
在页面中怎么调用它来输出表数据,给个例子好吗!
------解决方案--------------------//查看
public DataSet selnews()
{
string connString = System.Configuration.ConfigurationSettings.AppSettings[ "ConnectionString "];
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand( "select * from 你的表名 ",con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
------解决方案--------------------using System;
using System.Data;
using System.Data.SqlClient;
namespace DBAccess
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class DB
{
SqlConnection conn = new SqlConnection ( "server=(local);database=pubs;uid=sa;pwd=sa ");
SqlCommand cmd = new SqlCommand ();
public DB()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 执行存储过程,返回DataSet
/// </summary>
/// <param name= "cmd "> 存储过程参数数组 </param>
/// <param name= "proc "> 存储过程名 </param>
/// <returns> DataSet </returns>
public DataSet returnDataSet(string proc,SqlParameter[] paras)
{
this.cmd.Connection = conn;
this.cmd.CommandType = CommandType.StoredProcedure;
this.cmd.CommandText = proc;
if(paras!=null && paras.Length > 0)
{
foreach(SqlParameter p in paras)
{
cmd.Parameters.Add(p);
}
}
SqlDataAdapter da = new SqlDataAdapter ();
DataSet ds = new DataSet ();
da.Fill(ds);
return ds;
}
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name= "sql "> sql查询语句 </param>
/// <returns> </returns>
public DataSet returnDataSet(string sql)
{
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet ();
da.Fill(ds);
return ds;
}
}
}