c#连接数据库 Data Source=

2024-12-17 14:15:37
推荐回答(1个)
回答1:

sql的ConnDB.cs
------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
namespace MyWeb
{
///


/// ConnDB 的摘要说明。
///

public class ConnDB
{
public static string ConnStr="server=.;uid=sa;pwd=;database=northwind";
public ConnDB()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

public static SqlDataReader ExecuteReader(string sql)
{
SqlConnection conn=new SqlConnection(ConnStr);
SqlCommand cmd=new SqlCommand(sql,conn);
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

public static object ExecuteScalar(string sql)
{
SqlConnection conn=new SqlConnection(ConnStr);
SqlCommand cmd=new SqlCommand(sql,conn);
conn.Open();
object o=cmd.ExecuteScalar();
conn.Close();
return o;
}

public static int ExecuteNonQuery(string sql)
{
SqlConnection conn=new SqlConnection(ConnStr);
SqlCommand cmd=new SqlCommand(sql,conn);
conn.Open();
int i=cmd.ExecuteNonQuery();
conn.Close();
return i;
}

public static DataSet ExecuteDataSet(string sql)
{
SqlConnection conn=new SqlConnection(ConnStr);
SqlDataAdapter da=new SqlDataAdapter(sql,conn);
DataSet ds=new DataSet();
da.Fill(ds);
return ds;
}
}
}

------------------------------------------------------------------------------------------

Access的AccessConnDB.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;

///
/// AccessConnDB 的摘要说明
///

public class AccessConnDB
{
string connStr;
public AccessConnDB()
{
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data\\Tools.mdb") + ";Persist Security Info=False";

}

///
/// 对Access数据库执行查询操作
///

/// sql语句
///
public OleDbDataReader ExecuteReader(string cmdStr)
{
OleDbConnection conn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
conn.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

///
/// 对Access数据库执行增/删/改的操作
///

/// sql语句
///
public int ExecuteNonQuery(string cmdStr)
{
OleDbConnection conn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
conn.Open();
int i = cmd.ExecuteNonQuery();
conn.Close();
return i;
}

///
/// 执行查询,并返回结果集的第一行第一列
///

/// sql语句
///
public object ExecuteScalar(string cmdStr)
{
OleDbConnection conn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
conn.Open();
return cmd.ExecuteScalar();
}
}