class DataBase
{
SqlConnection myconn //作为数据库的链接对象
private String server = "localhost" //数据库的链接
private String database = "booksys" //数据库名称
private String username = "sa"//数据库的登录名
private String password = "123456"//数据库的密码
public bool databasecon()
{
string str = "server=" + server + "database=" + database + "uid=" + username + "pwd=" + password //构建字符串
try //试着去打开数据库
{
myconn = new SqlConnection(str)//新建链接,并按字符串链接
myconn.Open()//打开数据库
}
catch (Exception )//如果失败
{
return false
}
return true
}
public SqlConnection getconn()
{
return myconn
}
public void closeconn()
{
myconn.Close()
}
}
//这个是数据库链接的类,你也可以直接用,然后判断用户名是否为空,密码是否正确的代码,这里字数多了写不上去了
Web.config中配置<connectionStrings>
<add name="ConStr" connectionString="Data Source=数据库地址Initial Catalog=数据库名User ID=数据库登录名Password=数据库登录密码pooling=TrueMax Pool Size=1000Min Pool Size=5 " providerName="System.Data.SqlClient" />
</connectionStrings>
另可以创建一个数据库访问类
using System
using System.Web
using System.Configuration
using System.Data
using System.Data.SqlClient
using System.Reflection
/// <summary>
/// App_Conn 的摘要说明
/// </summary>
public class App_Conn
{
/// <summary>
/// 得到数据库的地址
/// </summary>
public static string ConnStr
{
get
{
return ConfigurationManager.ConnectionStrings["ConStr"].ToString().Trim()
}
}
public App_Conn()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 返回一个DataSet数据集
/// </summary>
/// <param name="MySQL"></param>
/// <returns></returns>
public static DataSet _DataSet(string MySQL)
{
SqlConnection m_con = new SqlConnection(ConnStr)
if (m_con.State != ConnectionState.Open)
{
m_con.Open()
}
SqlCommand cmd = new SqlCommand(MySQL, m_con)
SqlDataAdapter da = new SqlDataAdapter(cmd)
DataSet ds = new DataSet()
da.Fill(ds)
if (m_con.State == ConnectionState.Open)
{
m_con.Close()
m_con.Dispose()
}
return ds
}
/// <summary>
/// 执行SQL语句后,返回执行的行数
/// </summary>
/// <param name="MySQL"></param>
/// <returns></returns>
public static int _RowCount(string MySQL)
{
SqlConnection m_con = new SqlConnection(ConnStr)
if (m_con.State != ConnectionState.Open)
{
m_con.Open()
}
SqlCommand cmd = new SqlCommand(MySQL, m_con)
int rowscount = cmd.ExecuteNonQuery()
if (m_con.State == ConnectionState.Open)
{
m_con.Close()
m_con.Dispose()
}
return rowscount
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)