天天看點

鑄造 編碼規則_鑄造概論

鑄造 編碼規則

介紹 (Introduction)

本文是關于資料轉換的。 我将介紹VBA / VB6顯式轉換。 它與飛蠅釣魚,卷筒釣魚,沖浪釣魚,表演或斷肢沒有任何關系。 您可能已經進行了一些轉換,卻不知道,因為VB隐式為您執行了一些轉換。 盡管這是一個教程,但我包含了一些提示和技巧。

Firstly, I'd like to acknowledge the genesis of this article.  The primary impetus to start writing was reading Jim Dettman's excellent article (http:/A_12.html) on the MS-Access DLookup function.  Secondly, I had recently completed an upgrade to one of my Access applications using and enhancing the DLookup function with some data type casting.  Thirdly, from my involvement with the local Delphi user group and answering questions in the Delphi TA, I've become a fan of Delphi's QuotedStr() function.  In general, I look back on so many EE questions in various Topic Areas that involved data type casting, that I thought it worth writing an article.

首先,我想承認本文的起源。 開始撰寫文章的主要動力是閱讀Jim Dettman關于MS-Access DLookup函數的出色文章( http:/A_12.html )。 其次,我最近使用某些資料類型轉換并使用DLookup功能增強了對我的Access應用程式的更新。 第三,由于我參與了當地的Delphi使用者組并在Delphi TA中回答了問題,是以我成為了Delphi QuotedStr()函數的支援者。 總的來說,我回顧了涉及資料類型轉換的各個主題領域中的許多EE問題,我認為值得寫一篇文章。

文章主題 (Article Topics)

What is Casting?

什麼是鑄造?

Common places to encounter casting

常見的鑄件場所

Why would this ever be a problem?

為什麼這會成為問題?

Problems with casting

鑄造問題

Intrinsic Casting functions in VBA/VB6

VBA / VB6中的固有轉換功能

Casting Tricks & Tips

鑄造技巧

什麼是鑄造? (What is Casting?)

強制轉換會導緻變量的内容或表達式/文字被視為不同類型的資料。 資料轉換發生在臨時存儲位置。 有幾種方法可以在VB中轉換資料。 由于大多數人應該熟悉串聯,是以您應該了解串聯是字元串(資料類型)表達式之間的操作。 将數字或日期連接配接到字元串時,會有一些隐式轉換。 雖然有一些函數可以在更改資料類型的同時提取其一部分資料

(e.g. Format(Date(),"dddd")), this article is about a data type change of the entire data.

(例如Format(Date(),“ dddd”)),本文是關于整個資料的資料類型更改。

常見的鑄件場所 (Common places to encounter casting)

Dynamic SQL

- building a SQL statement through concatenation with local variables, control values and other database data.

動态SQL-

通過與局部變量,控制值和其他資料庫資料的連接配接來建構SQL語句。

VBA code

- converting a string to a byte array as the first part of an encryption routine.

VBA代碼

-将字元串轉換為位元組數組作為加密例程的第一部分。

Dim bText() As Byte

昏暗bText()作為位元組

bText = StrConv(parmPlainText, vbFromUnicode)

bText = StrConv(parmPlainText,vbFromUnicode)

Function and Subroutine calls

- defining a parameter as a particular data type may require the calling/invoking code to cast an express to a matching data type.  Also, a routine may have to cast data passed in through a Variant parameter.

函數和子例程調用

-将參數定義為特定的資料類型可能需要調用/調用代碼将Express轉換為比對的資料類型。 同樣,例程可能必須強制轉換通過Variant參數傳入的資料。

T-SQL

- If you have seen many T-SQL scripts, you have probably noticed the use of the CAST() and CONVERT() functions.  

T-SQL-

如果您看過許多T-SQL腳本,則可能已經注意到CAST()和CONVERT()函數的使用。

Excel

- has several workbook functions to cast one type of data into another, such as DEC2HEX(), DEC2BIN(), HEX2DEC(), COMPLEX().

Excel-

具有多個工作簿功能,可以将一種資料類型轉換為另一種資料類型,例如DEC2HEX(),DEC2BIN(),HEX2DEC(),COMPLEX()。

為什麼這會成為問題? (Why would this ever be a problem?)

有時候您會為了友善而犧牲便利性和靈活性。 如果您的程式讀取CSV檔案,則可能需要将這些值讀取到String或Variant資料類型的局部變量中,然後将某些資料轉換為特定的資料類型以供以後處理。

鑄造問題 (Problems with casting)

Sometimes you get an error message that doesn't quite describe casting as the solution

有時您會收到一條錯誤消息,并沒有将鑄造描述為解決方案

Error 13: Type Mismatch

錯誤13:類型不比對

Error 49: Bad DLL calling convention

錯誤49:錯誤的DLL調用約定

Error 1006: Unable to get the [property name] property of the [object] class

錯誤1006:無法擷取[object]類的[property name]屬性

VB var types are different than DB var types

VB var類型與DB var類型不同

x=#1/2/2009#:?x,vartype(x),vbvartype.vbDate,TypeName(x),dbDate
1/2/2009       7             7            Date           8 

x=1/2:?x,vartype(x),vbvartype.vbDouble,TypeName(x),dbDouble
 0.5           5             5            Double         7 

x=2009:?x,vartype(x),vbvartype.vbInteger,TypeName(x),dbInteger
 2009          2             2            Integer        3 

x=200900:?x,vartype(x),vbvartype.vbLong,TypeName(x),dbLong
 200900        3             3            Long           4 

x="aikimark":?x,vartype(x),vbvartype.vbString,TypeName(x),dbText
aikimark       8             8            String         10 

x=true:?x,vartype(x),vbvartype.vbBoolean,TypeName(x),dbBoolean
True           11            11           Boolean        1 
           

Sometimes the intrinsic casting functions don't work the way you expect (or want)

有時,固有的強制轉換功能無法按您期望的方式工作

date conversions 日期轉換
?cdate("1/2/2009")
1/2/2009 
?cdate(1/2/2009)
12:00:22 AM 
           
Number concatenation

-- which is why I always use the & concatenation operator

數字串聯

-這就是為什麼我總是使用&串聯運算符

a=1
b=2
?a + b
 3 
?cstr(a) + cstr(b)
12
           

VBA / VB6中的固有轉換功能 (Intrinsic Casting functions in VBA/VB6)

CBool()
CByte()
CCur()
CDate()
CDbl()
CDec()
CInt()
CLng()
CSng()
CStr()
CVar()
           
Note:

the .Net framework is full of casting features, such as the .ToString method.  I will not cover these in this article.

注意:

.Net架構具有強制轉換功能,例如.ToString方法。 我将不在本文中介紹這些内容。

鑄造技巧 (Casting Tricks & Tips)

Dynamic SQL 動态SQL

JDettman's article introduced you to delimited string variables in a DLookup() criteria parameter.  In addition, there are date variables, requiring a pound sign (#) delimiter.  Here is a general purpose function that you can use to properly delimit your variables, no matter what their data type. Sometimes we cast data by the delimiters around expressions we type into our code.  As Jim highlighted, the data type of the field needs to match the data type of the compared value/expression.  When they don't match we frequenly receive a "Data type mismatch in criteria expression" error (-2147217913), but sometimes, we just don't get the results we expected.  

JDettman的文章向您介紹了DLookup()标準參數中的定界字元串變量。 此外,還有日期變量,需要井号(#)分隔符。 這是一個通用函數,無論它們的資料類型如何,都可以使用它來正确地定界變量。 有時,我們使用定界符将資料鍵入到代碼中,然後使用定界符強制轉換資料。 正如Jim所強調的,字段的資料類型需要與比較值/表達式的資料類型比對。 當它們不比對時,我們通常會收到“條件表達式中的資料類型不比對”錯誤(-2147217913),但是有時,我們隻是無法獲得預期的結果。

Public Function Delimed(parmVar) As String
  Const QuoteChar = """"
  Const PoundChar = "#"
  If VarType(parmVar) = vbDate Or IsDate(parmVar) Then
    Delimed = PoundChar & parmVar & PoundChar
  ElseIf IsNumeric(parmVar) Then
    Delimed = CStr(parmVar)
  ElseIf VarType(parmVar) = vbString Then
    Delimed = QuoteChar & parmVar & QuoteChar
  Else
    Delimed = CStr(parmVar)
  End If
End Function
           
Usage: 用法:

This example revisits the DLookup article's example set, comparing column values in a table.

本示例重新通路DLookup文章的示例集,比較表中的列值。

Dim vCompany As Variant
Dim sCompany As String
Dim lCompany As Long
Dim vFrom As Variant
Dim vTo As Variant
Dim sSQL As String
Dim rs As Recordset
vCompany = 2525
sCompany = "2525"
lCompany = 2525
sSQL = "Select * From CompanyTable Where ID =" & Delimed(vCompany)
Debug.Print "vCompany=ID", sSQL
sSQL = "Select * From CompanyTable Where ID =" & Delimed(sCompany)
Debug.Print "sCompany=ID", sSQL
sSQL = "Select * From CompanyTable Where ID =" & Delimed(lCompany)
Debug.Print "lCompany=ID", sSQL

vCompany = "EE Publishing"
sCompany = "EE Publishing"
sSQL = "Select * From CompanyTable Where CompanyName =" & Delimed(vCompany)
Debug.Print "vCompany=CompanyName", sSQL
sSQL = "Select * From CompanyTable Where CompanyName =" & Delimed(sCompany)
Debug.Print "sCompany=CompanyName", sSQL

vFrom = "2001-10-1"
vTo = "10/11/2009"
sSQL = "Select * From CompanyTable Where JoinDate Between " & Delimed(vFrom) & " And " & Delimed(vTo)
Debug.Print "vFrom/vTo", sSQL
           

Result of the Delimed() function on the SQL string

SQL字元串上的Delimed()函數的結果

=== Immediate Window ============
vCompany=ID		Select * From CompanyTable Where ID =2525
sCompany=ID		Select * From CompanyTable Where ID =2525
lCompany=ID		Select * From CompanyTable Where ID =2525
vCompany=CompanyName	Select * From CompanyTable Where CompanyName ="EE Publishing"
sCompany=CompanyName	Select * From CompanyTable Where CompanyName ="EE Publishing"
vFrom/vTo		Select * From CompanyTable Where JoinDate Between #2001-10-1# And #10/11/2009#
=================================
           
Warning:

The Delimed() function is not perfect.  It can not overcome limitations in the runtime environment.  This is most evident with the following date example executed in the Immediate window.  If you ever created dynamic SQL with a date string that was not #-delimited, then this should help you understand what value was being passed to the database query parser.

警告:

Delimed()函數并不完美。 它無法克服運作時環境中的限制。 在立即視窗中執行以下日期示例時,這一點最為明顯。 如果您使用日期編号不是#分隔符建立動态SQL,那麼這應該可以幫助您了解将什麼值傳遞給資料庫查詢解析器。

=== Immediate Window ============
?Delimed("12/1/2001")
#12/1/2001#

?Delimed(12/1/2001)
5.99700149925037E-03
=================================
           
Casting for my own convenience 為自己友善鑄造

In a recent application, I created a configuration settings table to help with the migration of the database from development (me), to the on-site test environment, to the production environment.  Originally, there were two text columns, containing the config-name and config-value.  I used the DLookup() function to retrieve values from the table.  I ran into some quirks of the DLookup() function that cause me to add a third text column to the table (config-datatype) and wrap the DLoopkup results in a function that cast the results into the desired data type.  This made the application code much simpler.  When the database is opened, application code can match the attached table connection string against that in the configuration settings table and reattach them, if necessary.  There are certain actions that don't work in my development environment, so I look at the DevEnvironment config-value to detect this.  When the tester gets a new copy of the application, he renames the configuration settings tables and restarts the database.  He repeats this process when moving his tested database into production.

在最近的應用程式中,我建立了一個配置設定表,以幫助資料庫從開發(me)遷移到現場測試環境,再到生産環境。 最初,有兩個文本列,分别包含config-name和config-value。 我使用DLookup()函數從表中檢索值。 我遇到了DLookup()函數的一些怪癖,這些怪癖使我向表中添加了第三文本列(config-datatype),并将DLoopkup結果包裝到一個将結果轉換為所需資料類型的函數中。 這使應用程式代碼更加簡單。 打開資料庫後,應用程式代碼可以将附加的表連接配接字元串與配置設定表中的字元串進行比對,并在必要時重新附加它們。 有些操作在我的開發環境中不起作用,是以我檢視了DevEnvironment的配置值來檢測到這一點。 當測試人員獲得應用程式的新副本時,他将重命名配置設定表并重新啟動資料庫。 當他将測試的資料庫投入生産時,他重複了這一過程。

My DLookup() problems were:

我的DLookup()問題是:

The returned Variant data type isn't typed

未鍵入傳回的Variant資料類型

If a value isn't found, the function returns Null

如果找不到值,則該函數傳回Null

Null values may be fine for assigning to fields, but they can't be assigned to string variables and some controls

空值可能适合配置設定給字段,但是不能将它們配置設定給字元串變量和某些控件

Public Function GetConfigSetting(parmConfigName As String) As Variant
  Dim varValue As Variant
  Dim strType As String
  varValue = DLookup("ConfigValue", "ConfigurationSettings", "ConfigName = " & Delimed(parmConfigName))
  If IsNull(varValue) Then
    GetConfigSetting = vbNullString
  Else
    strType = DLookup("ConfigDataType", "ConfigurationSettings", "ConfigName = " & Delimed(parmConfigName))
    Select Case strType
      Case "Text"
        GetConfigSetting = CStr(varValue)
      Case "Long"
        GetConfigSetting = CLng(varValue)
      Case "Single"
        GetConfigSetting = CSng(varValue)
      Case "Double"
        GetConfigSetting = CDbl(varValue)
      Case "Date"
        GetConfigSetting = CDate(varValue)
      Case "Boolean"
        GetConfigSetting = CBool(varValue)
      Case Else
        GetConfigSetting = varValue
    End Select
  End If
End Function
           
ConfigurationSettings table ConfigurationSettings表
ID	ConfigName		ConfigValue				ConfigDataType
1	ImportPath		C:\Temp\					Text
2	DevEnvironment		True					Boolean
3	BE_Connect		C:\Specimen DB 9-3\Spec Database_BE.mdb	Text
4	ActivityLog_Connect 	C:\Specimen DB 9-3\Activity Log.mdb		Text
5	Snapshot_Connect       	C:\ Specimen DB 9-3\Spec Snapshot.mdb	Text
6	BE_Pattern		*_BE.mdb					Text
7	ActivityLog_Pattern  	*Activity Log.mdb				Text
8	Snapshot_Pattern    	*SpecDBMS Snapshot.mdb			Text

Fieldname		DataType 	FieldLength
ID			AutoNumber	4 
ConfigName		Text		50 
ConfigValue		Text		255 
ConfigDataType		Text		50 
           

ConfigDataType Lookup tab is defined as:

ConfigDataType查找頁籤定義為:

RowSource is a one column value list: Text;Long;Single;Double;Date;Boolean

RowSource是一列值清單:Text; Long; Single; Double; Da te; Boolean

BoundColumn: 1

綁定列:1

ColumnWidths: 2"

列寬:2英寸

========================================= ========================= ========== =====

====== BONUS  MATERIAL ==================

======獎勵材料==================

=========================================

========================= ========== =====

性能提示: (Performance Tip:)

大約十年前,我向本地VB使用者組進行了性能示範。 我的測試之一是Select Case語句,與在GetConfigSetting()函數中看到的非常相似。 如果建立将非常頻繁執行的配置設定表,則最好更改ConfigDataType字段查找頁籤。 整數值的比較比字元串值的比較要快得多。

Also, note that the ordering of compared values will also help performance, placing the most likely encountered values nearer to the top of the list.

另外,請注意,比較值的排序也将有助于提高性能,将最有可能遇到的值放在清單頂部附近。

ConfigDataType Lookup tab is defined as:

ConfigDataType查找頁籤定義為:

RowSource is a two column value list: 8;Text;3;Long;4;Single;5;Double;7;Date;11;Boolean

RowSource是兩列值清單:8; Text; 3; Long; 4; Single; 5; D ouble; 7; Da te; 11; Bool ean

BoundColumn: 1

綁定列:1

ColumnWidths: 0";2"

列寬:0“; 2”

High performance version of the GetConfigSetting() function:

高性能版本的GetConfigSetting()函數:

'===================================================
'Performance tweaked version of the casting function
'===================================================
Public Function GetConfigSetting(parmConfigName As String) As Variant
  Dim varValue As Variant
  Dim lngType As Long
  varValue = DLookup("ConfigValue", "ConfigurationSettings", "ConfigName = " & Delimed(parmConfigName))
  If IsNull(varValue) Then
    GetConfigSetting = vbNullString
  Else
    lngType = DLookup("ConfigDataType", "ConfigurationSettings", "ConfigName = " & Delimed(parmConfigName))
    Select Case lngType
      Case vbString
        GetConfigSetting = CStr(varValue)
      Case vbBoolean
        GetConfigSetting = CBool(varValue)
      Case vbLong
        GetConfigSetting = CLng(varValue)
      Case vbSingle
        GetConfigSetting = CSng(varValue)
      Case vbDouble
        GetConfigSetting = CDbl(varValue)
      Case vbDate
        GetConfigSetting = CDate(varValue)
      Case Else
        GetConfigSetting = varValue
    End Select
  End If
End Function
           

If this article was helpful, please click the

YES

link below.

如果本文對您有所幫助,請單擊下面的

“是”

連結。

翻譯自: https://www.experts-exchange.com/articles/1740/Introduction-to-Casting.html

鑄造 編碼規則