62,268
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace ExeciseProject.DAL
{
public class DBHelper
{
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter da;
private DataSet ds;
private string myServer;
private string myDatabase;
private string myUid;
private string myPwd;
private string myStrConn;
public DBHelper(string server, string database, string uid, string pwd)
{
//获取连接数据库语句的各个属性的值
this.myServer = server;
this.myDatabase = database;
this.myUid = uid;
this.myPwd = pwd;
try
{
conn = new SqlConnection(getStrConn());
}
catch
{
return null;
}
}
#region 封装连接数据库语句的属性
public string MyServer
{
//服务器地址
get { return myServer; }
set { myServer = value; }
}
public string MyDatabase
{
//数据库
get { return myDatabase; }
set { myDatabase = value; }
}
public string MyUid
{
//用户名
get { return myUid; }
set { myUid = value; }
}
public string MyPwd
{
// 密码
get { return myPwd; }
set { myPwd = value; }
}
#endregion
#region 组合数据库连接语句
private string getStrConn()
{
//组合连接数据库语句
try
{
connOpen();
myStrConn = "server=" + MyServer + ";database=" + MyDatabase + ";uid=" + MyUid + ";pwd=" + MyPwd;
connClose();
}
catch
{
return null;
}
return myStrConn;
}
#endregion
#region 打开数据库
private bool connOpen()
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
catch
{
return false;
}
return true;
}
#endregion
#region 关闭数据库
private bool connClose()
{
try
{
if(conn.State == ConnectionState.Open)
{
conn.Close();
}
}
catch
{
return false;
}
return true;
}
#endregion
#region 读取数据
public DataSet getDs(string strSelect,string tempTable)
{
// 读取数据库数据
try
{
da=new SqlDataAdapter(strSelect,conn);
ds = new DataSet();
da.Fill(ds,tempTable);
conn.Close;
}
catch
{
return null;
}
return ds.Tables[0];
}
#endregion
#region 写入数据
public bool setDb(string sql )
{
// 向数据库写入数据
try
{
if (conn.Open())
{
cmd = new SqlCommand(sql,conn);
da=cmd.ExecuteNonQuery();
connClose();
}
}
catch
{
return false;
}
return true;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace ExeciseProject.DAL
{
public class TestService
{
/// <summary>
/// 查询数据库表的数据
/// </summary>
public DataTable getTable(int num)
{
//查询数据库表的数据
int i=10; // 控制每页显示数据的行数
DataTable dt;
try
{
DBHelper db = new DBHelper(".", "Northeind", "sa", "123456");
string sql = "select top " + i + " * from Products where ProductID not in (select top " + ((num - 1) * i) + " ProductID from Products)";
if (i <= 0)
{
i = 1;
}
dt = db.getDs(sql,"table1");
}
catch
{
return null;
}
return dt;
}
}
}
