新聞中心
隨著大數(shù)據(jù)時代的到來,數(shù)據(jù)分析成為了企業(yè)管理必不可少的一環(huán)。利用數(shù)據(jù)庫中存儲的數(shù)據(jù),深入挖掘和分析數(shù)據(jù),可以幫助企業(yè)發(fā)掘商業(yè)機會,提高營銷效果,優(yōu)化經(jīng)營管理。而ADO.NET正是一種常用的.NET框架下對數(shù)據(jù)庫進行操作的技術(shù),本文將介紹如何。

專注于為中小企業(yè)提供成都網(wǎng)站制作、成都做網(wǎng)站服務(wù),電腦端+手機端+微信端的三站合一,更高效的管理,為中小企業(yè)常山免費做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動了近千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實現(xiàn)規(guī)模擴充和轉(zhuǎn)變。
一、ADO.NET簡介
ADO.NET是.NET框架中的一部分,是一種用于訪問數(shù)據(jù)庫的技術(shù)。它包含了多個數(shù)據(jù)訪問類,包括連接(Connection)、操作(Command)、讀取(DataReader)等,使開發(fā)者可以輕松地連接和管理關(guān)系型數(shù)據(jù)庫。
二、使用ADO.NET實現(xiàn)數(shù)據(jù)庫統(tǒng)計分析
1.建立數(shù)據(jù)庫連接
使用ADO.NET時,首先需要建立數(shù)據(jù)庫連接。在.NET中,SqlConnection類用于建立與SQL Server數(shù)據(jù)庫的連接,OleDbConnection類用于建立與Access或Excel數(shù)據(jù)庫的連接等。下面以SqlConnection類為例:
“`csharp
string connectionString = “Data Source=yourSQLServer;Initial Catalog=yourDatabase;Persist Security Info=True;User ID=yourUserName;Password=yourPassword”; //建立連接字符串
SqlConnection conn = new SqlConnection(connectionString); //建立數(shù)據(jù)庫連接
try
{
conn.Open(); //打開連接
//連接成功后,可以進行下一步操作
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //連接失敗后輸出錯誤信息
}
finally
{
conn.Close(); //關(guān)閉連接
}
“`
2.執(zhí)行SQL語句
建立好連接后,就可以執(zhí)行SQL語句了。使用ADO.NET可以通過兩種方式執(zhí)行SQL語句,一種是使用Command對象,一種是使用DataAdapter對象。
“`csharp
//使用Command執(zhí)行SQL語句
string sqlCommand = “SELECT * FROM yourTable WHERE yourCondition”;
SqlCommand cmd = new SqlCommand(sqlCommand, conn);
try
{
SqlDataReader reader = cmd.ExecuteReader(); //執(zhí)行查詢操作
//讀取查詢結(jié)果
while (reader.Read())
{
//輸出查詢結(jié)果
Console.WriteLine(reader[“ColumnName”].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //輸出錯誤信息
}
finally
{
cmd.Connection.Close(); //關(guān)閉連接
}
“`
“`csharp
//使用DataAdapter執(zhí)行SQL語句
string sqlCommand = “SELECT * FROM yourTable WHERE yourCondition”;
SqlDataAdapter da = new SqlDataAdapter(sqlCommand, conn);
DataSet ds = new DataSet(); //建立一個DataSet對象用于存儲查詢結(jié)果
try
{
da.Fill(ds); //將查詢結(jié)果填充到DataSet對象中
DataTable dt = ds.Tables[0]; //獲取之一個DataTable對象
//讀取DataTable中的數(shù)據(jù)
foreach (DataRow row in dt.Rows)
{
//輸出查詢結(jié)果
Console.WriteLine(row[“ColumnName”].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //輸出錯誤信息
}
finally
{
conn.Close(); //關(guān)閉連接
}
“`
3.數(shù)據(jù)統(tǒng)計分析
使用ADO.NET提供的數(shù)據(jù)訪問類,可以方便地實現(xiàn)數(shù)據(jù)統(tǒng)計分析。下面以查詢每個地區(qū)銷售額的總和為例,介紹如何使用ADO.NET進行數(shù)據(jù)分析。
“`csharp
string sqlCommand = “SELECT region, SUM(sales) AS totalSales FROM yourTable GROUP BY region”;
SqlDataAdapter da = new SqlDataAdapter(sqlCommand, connectionString);
DataSet ds = new DataSet(); //建立一個DataSet對象用于存儲查詢結(jié)果
try
{
da.Fill(ds); //將查詢結(jié)果填充到DataSet對象中
DataTable dt = ds.Tables[0]; //獲取之一個DataTable對象
//讀取DataTable中的數(shù)據(jù)
foreach (DataRow row in dt.Rows)
{
//輸出統(tǒng)計結(jié)果
Console.WriteLine(row[“region”].ToString() + ” : ” + row[“totalSales”].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //輸出錯誤信息
}
finally
{
conn.Close(); //關(guān)閉連接
}
“`
以上代碼中的SQL語句使用了SUM()函數(shù)和GROUP BY子句,可以統(tǒng)計每個地區(qū)銷售額的總和。使用ADO.NET提供的DataAdapter類可以將查詢結(jié)果填充到DataSet對象中,通過讀取DataSet中的數(shù)據(jù)可以方便地進行數(shù)據(jù)分析。
三、
本文介紹了如何。通過建立數(shù)據(jù)庫連接、執(zhí)行SQL語句和數(shù)據(jù)統(tǒng)計分析三個步驟,可以方便地對數(shù)據(jù)庫中的數(shù)據(jù)進行深入挖掘和分析,為企業(yè)在商業(yè)決策和管理中提供重要的參考依據(jù)。
成都網(wǎng)站建設(shè)公司-創(chuàng)新互聯(lián),建站經(jīng)驗豐富以策略為先導(dǎo)10多年以來專注數(shù)字化網(wǎng)站建設(shè),提供企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計,響應(yīng)式網(wǎng)站制作,設(shè)計師量身打造品牌風格,熱線:028-86922220ado.net快速上手實踐篇(二)
五、dal層數(shù)據(jù)訪問實現(xiàn)
在這里我們使用前一篇文章里實現(xiàn)的數(shù)據(jù)持久化層和偽SqlMapper對象,實現(xiàn)數(shù)據(jù)操作。下面我們來看看Dal下缺友核心的Dao如何實現(xiàn):
還記得我們在下面的dao類是怎么實現(xiàn)的嗎?沒錯,我們前陸根據(jù)一個基類BaseDAO和它的構(gòu)造函數(shù),實現(xiàn)dao的配置加載。但是樓豬的實現(xiàn)沒有那么復(fù)雜和強大,本文的實現(xiàn)其實就是通過BaseDAO和構(gòu)造函數(shù)獲取數(shù)據(jù)庫連接對象的key,初始化一個SqlMapper,然后利用SqlMapper對象進行基本的CRUD等等數(shù)據(jù)操作。那么我們?nèi)绾卫肂aseDAO和構(gòu)造函數(shù)就像以慧扮頃前在系列文章里的提到的Dal層下那樣進行SqlMapper的初始化呢?
1、在AdoNetDataaccess.Mapper下我們定義公共的BaseDAO類
代碼
namespace AdoNetDataAccess.Mapper
{
public abstract class BaseDAO
{
#region PRoperties
public SqlMapper SqlMapper { get; set; }
#endregion
#region Constructor
private BaseDAO()
{
}
/// summary
/// SqlMapper屬性適用
/// /summary
/// param name=”mapperName”/param
public BaseDAO(string mapperName)
{
this.SqlMapper = MapperUtill.GetMapper(mapperName);
}
#endregion
}
}
2、初始化SqlMapper的實用類
代碼
using System;
using System.Collections.Generic;
using System.Configuration;
namespace AdoNetDataAccess.Mapper
{
using AdoNetDataAccess.Core.Contract;
using AdoNetDataAccess.Core.Implement;
public sealed class MapperUtill
{
#region fields
public static string currentSqlKey = “sqlConn”;
public static int cmdTimeOut = 15;
private static readonly object objSync = new object();
private static readonly IDictionarystring, SqlMapper dictMappers = new Dictionarystring, SqlMapper();
#endregion
#region constructor and methods
private MapperUtill()
{
}
static MapperUtill()
{
try
{
cmdTimeOut = int.Parse(ConfigurationManager.AppSettings);
}
catch
{
cmdTimeOut = 15;
}
//實例化SqlDbMapper
for (int i = 0; i
ConfigurationManager.ConnectionStrings.Count; i++)
{
string key = ConfigurationManager.ConnectionStrings.Name;
string value = ConfigurationManager.ConnectionStrings.ConnectionString;
CreateMapper(key, value, cmdTimeOut);
}
}
public static SqlMapper GetSqlMapper(string key)
{
return MapperUtill.GetMapper(key);
}
public static SqlMapper GetCurrentSqlMapper()
{
return MapperUtill.GetMapper(currentSqlKey);
}
public static void CreateMapper(string connKey, string sqlConStr, int connTimeOut)
{
IDbOperation operation = new SqlServer(sqlConStr, connTimeOut);
SqlMapper mapper = new SqlMapper(operation);
dictMappers.Add(connKey.ToUpper().Trim(), mapper);//不區(qū)分大小寫
}
public static SqlMapper GetMapper(string sqlConKey)
{
if (string.IsNullOrEmpty(sqlConKey))
{
throw new Exception(“數(shù)據(jù)庫連接字符串主鍵為空!”);
}
sqlConKey = sqlConKey.ToUpper();//不區(qū)分大小寫
SqlMapper mapper = null;
if (dictMappers.ContainsKey(sqlConKey))
{
mapper = dictMappers;
}
else
{
throw new Exception(string.Format(“沒有{0}所對應(yīng)的數(shù)據(jù)庫連接”, sqlConKey));
}
return mapper;
}
/// summary
/// 釋放所有
/// /summary
public void Release()
{
foreach (KeyValuePairstring, SqlMapper kv in dictMappers)
{
SqlMapper mapper = kv.Value;
if (mapper == null)
{
continue;
}
mapper.CurrentDbOperation.CloseConnection();
}
dictMappers.Clear();
}
#endregion
}
}
這個實用類的重要作用就是初始化配置文件里connectionStrings配置節(jié)點,以獲取sql連接對象必須的連接字符串。
3、PersonDao類
下面就是針對具體的Person表的數(shù)據(jù)操作了:
代碼
using System.Collections.Generic;
using System.Data;
namespace AdoNetDataAccess.Dal.Dao
{
using AdoNetDataAccess.Dal.Model;
using AdoNetDataAccess.Dal.Utility;
using AdoNetDataAccess.Mapper;
public class PersonDao : BaseDAO
{
public PersonDao()
{
}
public int Insert(string sqlInsert)
{
int id = this.SqlMapper.Insert(sqlInsert);
//object obj = this.SqlMapper.ExecuteScalar(sqlInsert, System.Data.CommandType.Text, null);
return id;
}
public bool BatchInsert(IListPerson listModels)
{
int batchSize = 50000;
int copyTimeOut = 60;
DataTable dt = DataTableHelper.CreateTablePerson(listModels);
bool flag = this.SqlMapper.BatchInsert(typeof(Person).Name, batchSize, copyTimeOut, dt);
return flag;
}
public int Update(string sqlUpdate)
{
int result = this.SqlMapper.Update(sqlUpdate);
return result;
}
public IListPerson SelectPersons(string sqlSelect)
{
IListPerson listPersons = this.SqlMapper.QueryForListPerson(sqlSelect);
return listPersons;
}
public IDictionaryint, Person SelectDictPersons(string sqlSelect)
{
IDictionaryint, Person dictPersons = this.SqlMapper.QueryForDictionaryint, Person(“Id”, sqlSelect);
return dictPersons;
}
public DataTable SelectPersonTable(string sqlSelect)
{
DataTable dt = this.SqlMapper.FillDataTable(sqlSelect, CommandType.Text, null);
return dt;
}
public DataSet SelectPersonDataSet(string sqlSelect)
{
DataSet ds = this.SqlMapper.FillDataSet(sqlSelect, CommandType.Text, null);
return ds;
}
public int Delete(string sqlDelete)
{
int result = this.SqlMapper.Delete(sqlDelete);
return result;
}
}
}
到這里,一個dao類操作就實現(xiàn)了。然后我們按步就班實現(xiàn)對外調(diào)用的服務(wù)接口。在表現(xiàn)層調(diào)用吧。
六、表現(xiàn)層的調(diào)用
1、配置文件
代碼
appSettings
add key=”db_timeOut” value=”5000″/
/appSettings
connectionStrings
add name=”sqlConn” connectionString=”Data Source=.sqlexpress; Initial Catalog=TestDb; User Id=sa; PassWord=123456;”/
add name=”sqlConnStr1″ connectionString=”Data Source=.sqlexpress; Initial Catalog=TestDb; User Id=sa; Password=123456;”/
add name=”sqlConnStr2″ connectionString=”Data Source=.sqlexpress; Initial Catalog=TestDb; User Id=sa; Password=123456;”/
/connectionStrings
其中,connectionString是必須的,如果沒有,我們無法加載調(diào)用可用的SqlMapper。
2、CRUD操作測試
代碼
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
namespace OOXXWebApp
{
using AdoNetDataAccess.Dal;
using AdoNetDataAccess.Dal.Model;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//增刪改查測試
string sqlInsert = “INSERT Person (FirstName,LastName,Weight,Height) VALUES( ‘jeff’,’wong’,70,180) SELECT @@IDENTITY FROM Person(NOLOCK)”;
string sqlUpdate = “UPDATE Person SET Height=178 WHERE Id=1”;
string sqlSelect = “SELECT TOP 100 * FROM Person(NOLOCK)”;
string sqlDelete = “DELETE Person WHERE Id10 AND Id100”;
IListPerson listModels = new ListPerson();
for (int i = 0; i
500000; i++)
{
Person model = new Person();
model.FirstName = “Jeff”;
model.LastName = “Wong”;
model.Weight = 70;
model.Height = 180;
listModels.Add(model);
}
Response.Write(“Test Beginning……br/”);
int id = ServiceFactory.CreatePersonService().Add(sqlInsert);
Response.Write(string.Format(“br/Insert and return id:{0}”, id));
bool flag = ServiceFactory.CreatePersonService().BatchInsert(listModels);
Response.Write(string.Format(“br/ Batch Insert {0}”, flag ? “succeed” : “failed”));
IListPerson listPersons = ServiceFactory.CreatePersonService().GetPersons(sqlSelect);
Response.Write(string.Format(“br/Select pesons and return persons:{0}”, listPersons.Count));
IDictionaryint, Person dictPersons = ServiceFactory.CreatePersonService().GetDictPersons(sqlSelect);
Response.Write(string.Format(“br/Select pesons and return dictionary persons:{0}”, dictPersons.Count));
DataTable dt = ServiceFactory.CreatePersonService().GetPersonTable(sqlSelect);
Response.Write(string.Format(“br/Select pesons and return persons:{0}”, dt.Rows.Count));
DataSet ds = ServiceFactory.CreatePersonService().GetPersonDataSet(sqlSelect);
Response.Write(string.Format(“br/Select pesons and return persons:{0}”, ds.Tables.Rows.Count));
int affectNum = ServiceFactory.CreatePersonService().Modify(sqlUpdate);
Response.Write(string.Format(“br/Update and affect rows :{0}”, affectNum));
affectNum = 0;
affectNum = ServiceFactory.CreatePersonService().Remove(sqlDelete);
Response.Write(string.Format(“br/Delete and affect rows :{0}”, affectNum));
Response.Write(“br/br/Test End.”);
}
}
}
}
這個就不用多說了吧,表現(xiàn)層寫SQL語句調(diào)用寫好的服務(wù)就行了。比較不舒服的地方就是SQL語句不得不寫在類里面,如果自動生成或者獨立放在xml下實現(xiàn)可配置的形式那就更好了,當然sql語句不是我們討論的重點,您有好的方法可以自己擴展實現(xiàn)更人性化的功能,減少書寫SQLl語句的工作。
七、最后,對demo工程文件結(jié)構(gòu)進行簡單說明。
1、數(shù)據(jù)持久化層AdoNetDataAccess.Core
2、SqlMapper層AdoNetDataAccess.Mapper(引用AdoNetDataAccess.Core)
3、具體數(shù)據(jù)操作使用層AdoNetDataAccess.Dal(引用AdoNetDataAccess.Mapper)
ado.net 數(shù)據(jù)庫統(tǒng)計的介紹就聊到這里吧,感謝你花時間閱讀本站內(nèi)容,更多關(guān)于ado.net 數(shù)據(jù)庫統(tǒng)計,使用ADO.NET實現(xiàn)數(shù)據(jù)庫統(tǒng)計分析功能,ado.net快速上手實踐篇(二)的信息別忘了在本站進行查找喔。
成都創(chuàng)新互聯(lián)科技公司主營:網(wǎng)站設(shè)計、網(wǎng)站建設(shè)、小程序制作、成都軟件開發(fā)、網(wǎng)頁設(shè)計、微信開發(fā)、成都小程序開發(fā)、網(wǎng)站制作、網(wǎng)站開發(fā)等業(yè)務(wù),是專業(yè)的成都做小程序公司、成都網(wǎng)站建設(shè)公司、成都做網(wǎng)站的公司。創(chuàng)新互聯(lián)公司集小程序制作創(chuàng)意,網(wǎng)站制作策劃,畫冊、網(wǎng)頁、VI設(shè)計,網(wǎng)站、軟件、微信、小程序開發(fā)于一體。
網(wǎng)站名稱:使用ADO.NET實現(xiàn)數(shù)據(jù)庫統(tǒng)計分析功能(ado.net數(shù)據(jù)庫統(tǒng)計)
本文網(wǎng)址:http://fisionsoft.com.cn/article/dhhegsp.html


咨詢
建站咨詢
