新聞中心
在使用數(shù)據(jù)庫時(shí),處理時(shí)間數(shù)據(jù)總是一個(gè)重要的任務(wù)。因?yàn)闀r(shí)間數(shù)據(jù)的正確性直接影響到數(shù)據(jù)查詢和應(yīng)用程序的可靠性。本文將深入介紹ADO.NET如何處理數(shù)據(jù)庫時(shí)間,為讀者提供更多關(guān)于時(shí)間數(shù)據(jù)的信息。

1. 時(shí)間數(shù)據(jù)類型
在大多數(shù)關(guān)系數(shù)據(jù)庫中,時(shí)間數(shù)據(jù)類型通常包括日期時(shí)間、時(shí)間戳等。不同的數(shù)據(jù)庫管理系統(tǒng)可能有不同的時(shí)間數(shù)據(jù)類型,它們可以通過ADO.NET提供的一些類進(jìn)行映射。以下是一些常見的時(shí)間數(shù)據(jù)類型:
– datetime: 表示一個(gè)日期和時(shí)間值,它的精度可達(dá)到秒級別。在SQL Server中,它的取值范圍為”1753/1/1 00:00:00″到”9999/12/31 23:59:59″。
– datetime2: 表示一個(gè)日期和時(shí)間值,它的精度可達(dá)到各種級別,從100納秒到1微秒不等。在SQL Server中,它的取值范圍與datetime相同。
– time: 表示一個(gè)時(shí)間值,可以精確到秒、毫秒或者微秒。它的取值范圍為”00:00:00″到”23:59:59.9999999″。
– timestamp: 表示一個(gè)二進(jìn)制值,它在數(shù)據(jù)庫中用于實(shí)現(xiàn)數(shù)據(jù)行的版本控制。它的大小為8字節(jié),由數(shù)據(jù)庫自動(dòng)生成。
2. 處理時(shí)間數(shù)據(jù)
在使用ADO.NET處理時(shí)間數(shù)據(jù)時(shí),需要注意以下幾點(diǎn):
2.1. 存儲(chǔ)時(shí)間數(shù)據(jù)
在向數(shù)據(jù)庫中存儲(chǔ)時(shí)間數(shù)據(jù)時(shí),需要將時(shí)間數(shù)據(jù)轉(zhuǎn)換成數(shù)據(jù)庫中的時(shí)間數(shù)據(jù)類型。例如,在SQL Server中,可以使用datetime或datetime2數(shù)據(jù)類型來存儲(chǔ)日期時(shí)間信息。在進(jìn)行數(shù)據(jù)插入或更新操作時(shí),需要使用以下代碼將時(shí)間數(shù)據(jù)轉(zhuǎn)換成數(shù)據(jù)庫中的數(shù)據(jù)類型:
“`
DateTime dateTime = DateTime.Now;
SqlParameter param = new SqlParameter(“@DateTime”, SqlDbType.DateTime);
param.Value = dateTime;
“`
2.2. 獲取時(shí)間數(shù)據(jù)
在從數(shù)據(jù)庫中獲取時(shí)間數(shù)據(jù)時(shí),需要使用DataReader對象的GetDateTime()方法來獲取DateTime類型的時(shí)間值。例如,以下代碼查詢數(shù)據(jù)庫中的時(shí)間數(shù)據(jù)并顯示到控制臺上:
“`
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(“SELECT CreationTime FROM Users WHERE Id = @Id”, conn);
cmd.Parameters.AddWithValue(“@Id”, 1);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
DateTime creationTime = reader.GetDateTime(0);
Console.WriteLine(creationTime.ToString());
}
reader.Close();
}
“`
2.3. 處理不同的時(shí)間數(shù)據(jù)類型
如果數(shù)據(jù)庫中存儲(chǔ)的時(shí)間數(shù)據(jù)類型與.NET中的時(shí)間數(shù)據(jù)類型不同,需要使用Convert類或者DateTime.Parse()方法來將數(shù)據(jù)類型進(jìn)行轉(zhuǎn)換。以下是一個(gè)例子:
“`
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(“SELECT StartTime FROM Schedule WHERE Id = @Id”, conn);
cmd.Parameters.AddWithValue(“@Id”, 1);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string startTime = reader.GetString(0);
DateTime dt = DateTime.Parse(startTime);
Console.WriteLine(dt.ToString());
}
reader.Close();
}
“`
3. 時(shí)區(qū)處理
在分布式應(yīng)用程序中,時(shí)區(qū)處理是一個(gè)復(fù)雜的問題。由于不同的地理位置使用不同的時(shí)區(qū),這可能會(huì)導(dǎo)致時(shí)間數(shù)據(jù)的混亂。因此,了解如何在應(yīng)用程序中正確處理時(shí)區(qū)是很重要的。
在.NET中,可以使用TimeZoneInfo類來處理時(shí)區(qū)。它提供了一些方法來將本地時(shí)間轉(zhuǎn)換為協(xié)調(diào)世界時(shí)(UTC)或?qū)TC時(shí)間轉(zhuǎn)換為指定時(shí)區(qū)的時(shí)間。以下是一個(gè)例子:
“`
DateTime localTime = new DateTime(2023, 1, 1, 14, 0, 0);
TimeZoneInfo chinaZone = TimeZoneInfo.FindSystemTimeZoneById(“China Standard Time”);
DateTime chinaTime = TimeZoneInfo.ConvertTime(localTime, chinaZone);
Console.WriteLine(“Local time: {0}”, localTime);
Console.WriteLine(“China time: {0}”, chinaTime);
“`
4.
在本文中,我們深入討論了ADO.NET如何處理數(shù)據(jù)庫時(shí)間。我們介紹了常見的時(shí)間數(shù)據(jù)類型,包括datetime、datetime2、time和timestamp。我們介紹了如何存儲(chǔ)和獲取時(shí)間數(shù)據(jù),以及如何處理不同的時(shí)間數(shù)據(jù)類型。我們介紹了如何處理時(shí)區(qū)問題。了解這些內(nèi)容對于正確地處理時(shí)間數(shù)據(jù)是很重要的。
成都網(wǎng)站建設(shè)公司-創(chuàng)新互聯(lián)為您提供網(wǎng)站建設(shè)、網(wǎng)站制作、網(wǎng)頁設(shè)計(jì)及定制高端網(wǎng)站建設(shè)服務(wù)!
ado.net快速上手實(shí)踐篇(二)
五、dal層數(shù)據(jù)訪問實(shí)現(xiàn)
在這里我們使用前一篇文章里實(shí)現(xiàn)的數(shù)據(jù)持久化層和偽SqlMapper對象,實(shí)現(xiàn)數(shù)據(jù)操作。下面我們來看看Dal下缺友核心的Dao如何實(shí)現(xiàn):
還記得我們在下面的dao類是怎么實(shí)現(xiàn)的嗎?沒錯(cuò),我們前陸根據(jù)一個(gè)基類BaseDAO和它的構(gòu)造函數(shù),實(shí)現(xiàn)dao的配置加載。但是樓豬的實(shí)現(xiàn)沒有那么復(fù)雜和強(qiáng)大,本文的實(shí)現(xiàn)其實(shí)就是通過BaseDAO和構(gòu)造函數(shù)獲取數(shù)據(jù)庫連接對象的key,初始化一個(gè)SqlMapper,然后利用SqlMapper對象進(jìn)行基本的CRUD等等數(shù)據(jù)操作。那么我們?nèi)绾卫肂aseDAO和構(gòu)造函數(shù)就像以慧扮頃前在系列文章里的提到的Dal層下那樣進(jìn)行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的實(shí)用類
代碼
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;
}
//實(shí)例化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
}
}
這個(gè)實(shí)用類的重要作用就是初始化配置文件里connectionStrings配置節(jié)點(diǎn),以獲取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;
}
}
}
到這里,一個(gè)dao類操作就實(shí)現(xiàn)了。然后我們按步就班實(shí)現(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.”);
}
}
}
}
這個(gè)就不用多說了吧,表現(xiàn)層寫SQL語句調(diào)用寫好的服務(wù)就行了。比較不舒服的地方就是SQL語句不得不寫在類里面,如果自動(dòng)生成或者獨(dú)立放在xml下實(shí)現(xiàn)可配置的形式那就更好了,當(dāng)然sql語句不是我們討論的重點(diǎn),您有好的方法可以自己擴(kuò)展實(shí)現(xiàn)更人性化的功能,減少書寫SQLl語句的工作。
七、最后,對demo工程文件結(jié)構(gòu)進(jìn)行簡單說明。
1、數(shù)據(jù)持久化層AdoNetDataAccess.Core
2、SqlMapper層AdoNetDataAccess.Mapper(引用AdoNetDataAccess.Core)
3、具體數(shù)據(jù)操作使用層AdoNetDataAccess.Dal(引用AdoNetDataAccess.Mapper)
關(guān)于ado.net 數(shù)據(jù)庫時(shí)間的介紹到此就結(jié)束了,不知道你從中找到你需要的信息了嗎 ?如果你還想了解更多這方面的信息,記得收藏關(guān)注本站。
創(chuàng)新互聯(lián)-老牌IDC、云計(jì)算及IT信息化服務(wù)領(lǐng)域的服務(wù)供應(yīng)商,業(yè)務(wù)涵蓋IDC(互聯(lián)網(wǎng)數(shù)據(jù)中心)服務(wù)、云計(jì)算服務(wù)、IT信息化、AI算力租賃平臺(智算云),軟件開發(fā),網(wǎng)站建設(shè),咨詢熱線:028-86922220
網(wǎng)頁標(biāo)題:深入了解ADO.NET:如何處理數(shù)據(jù)庫時(shí)間(ado.net數(shù)據(jù)庫時(shí)間)
本文URL:http://fisionsoft.com.cn/article/djdpcgc.html


咨詢
建站咨詢
