数据库连接字符串中非法字符_在运行时动态构造数据库连接字符串

数据库连接字符串中非法字符

 Once you have finished your Delphi database solution, the final step is to successfully deploy it the user's computer.

完成Delphi数据库解决方案后 ,最后一步是将其成功部署到用户计算机上。

ConnectionString即时 ( ConnectionString On-The-Fly )

If you were using dbGo (ADO) components, theConnectionString property of the TADOConnection specifies the connection information for the data store.

如果您使用的是dbGo(ADO)组件,则TADOConnectionConnectionString属性指定数据存储的连接信息。

Obviously, when creating database applications that are to be run on various machines, the connection to the data source should not be hard-coded in the executable. In other words, the database may be located anywhere on the user's computer (or on some other computer in a network) — the connection string used in the TADOConnection object must be created at run time. One of the suggested places to store the connection string parameters is the Windows Registry (or, you might decide to use the "plain" INI files).

显然,在创建要在各种计算机上运行的数据库应用程序时,不应在可执行文件中硬编码与数据源的连接。 换句话说,数据库可以位于用户计算机上(或网络中某些其他计算机上)的任何位置-必须在运行时创建TADOConnection对象中使用的连接字符串。 Windows注册表是存储连接字符串参数的建议位置之一(或者,您可能决定使用“普通” INI文件 )。

In general, to create the connection string at run time you have to   a) place the Full Path to the database in Registry; and   b) each time you start your application, read the information from the Registry, "create" the ConnectionString and "open" the ADOConnection.

通常,要在运行时创建连接字符串,必须:a)将数据库的完整路径放在注册表中; b)每次启动应用程序时,请从注册表中读取信息,“创建” ConnectionString,并“打开” ADOConnection。

数据库...连接! ( Database... Connect! )

To help you understand the process, we've created a sample "skeleton" application consisting of one form (main form of the application) and a data module. Delphi's Data Modules provide a convenient organizational tool that is used to isolate the parts of your application that handle database connectivity and business rules.

为了帮助您理解该过程,我们创建了一个示例“骨架”应用程序,该应用程序由一种形式(应用程序的主要形式)和一个数据模块组成。 Delphi的数据模块提供了一种方便的组织工具,该工具用于隔离应用程序中处理数据库连接性和业务规则的部分。

The OnCreate event of the Data Module is where you place the code to dynamically construct the ConnectionString and connect to the database.

数据模块的OnCreate事件是放置代码以动态构造ConnectionString并连接到数据库的地方。


procedure TDM.DataModuleCreate(Sender: TObject);
begin
if DBConnect then
ShowMessage('Connected to Database!')
else
ShowMessage('NOT connected to Database!');
end;

Note: The name of the Data Module is "DM". The name of the TADOConnection component is "AdoConn".

注意 :数据模块的名称为“ DM”。 TADOConnection组件的名称为“ AdoConn”。

The DBConnect function does the actual work of connecting to the database, here's the code:

DBConnect函数完成连接数据库的实际工作,下面是代码:


function TDM.DBConnect: boolean;
var
conStr : string;
ServerName, DBName : string;
begin
ServerName := ReadRegistry('DataSource');
DBName := ReadRegistry('DataCatalog');
conStr := 'Provider=sqloledb;' +
'Data Source=' + ServerName + ';'+
'Initial Catalog=' + DBName + ';'+
'User Id=myUser;Password=myPasword';
Result := false;
AdoConn.Close;
AdoConn.ConnectionString := conStr;
AdoConn.LoginPrompt := False;
if (NOT AdoConn.Connected) then
try
AdoConn.Open;
Result:=True;
except on E:Exception do
begin
MessageDlg('There was an error connecting to
the database. Error:' + #13#10 +
e.Message,
mtError, [mbOk],0);
if NOT TDatabasePromptForm.Execute(ServerName, DBName)
then
Result := false
else
begin
WriteRegistry('DataSource', ServerName);
WriteRegistry('DataCatalog', DBName);
//recall this function
Result := DBConnect;
end;
end;
end;
end; //DBConnect

The DBConnect function connects to the MS SQL Server database — the ConnectionString is constructed using the local connStr variable.

DBConnect函数连接到MS SQL Server数据库-使用本地connStr变量构造ConnectionString。

The name of the database server is stored in the ServerName variable, the name of the database is held in the DBName variable. The function starts by reading those two values from the registry (using the custom ReadRegistry() procedure). Once the ConnectionString is assembled, we simply call then AdoConn.Open method. If this call returns "true", we have successfully connected to the database. 

数据库服务器的名称存储在ServerName变量中,数据库的名称保留在DBName变量中。 该函数首先从注册表中读取这两个值(使用自定义ReadRegistry()过程)。 组装好ConnectionString之后,我们只需调用AdoConn.Open方法即可。 如果此调用返回“ true”,则说明我们已成功连接到数据库。

Note: Since we are explicitly passing login information through the ConnectionString, the Since the data module is created before the main form, you can safely call the methods from the data module in the MainForm's OnCreate event.LoginPrompt property is set to false to prevent an unnecessary login dialog.

注意:由于我们是通过ConnectionString显式传递登录信息的,因此由于数据模块是在主窗体之前创建的,因此您可以在MainForm的OnCreate事件中安全地从数据模块中调用方法。 LoginPrompt属性设置为false,以防止不必要的登录对话框。

The "fun" starts if an exception occurs. While there might be many reasons for the Open method to fail, let's presume that the server name or the database name is bad.If this is the case, we'll give a chance to the user to specify the correct parameters by displaying a custom dialog form. The sample application also contains one additional form (DatabasePromptForm) that enables the user to specify the server and the database name for the Connection component. This simple form only provides two edit boxes, if you want to provide a more user-friendly interface, you could add two ComboBoxes and fill those by enumerating available SQL Servers and retrieving databases on a SQL Server.

如果发生异常,则“乐趣”开始。 虽然可能有很多原因导致Open方法失败,但我们假设服务器名称或数据库名称不正确,在这种情况下,我们将为用户提供一个通过显示自定义来指定正确参数的机会对话形式。 该示例应用程序还包含一种其他形式(DatabasePromptForm),该形式使用户可以指定连接组件的服务器和数据库名称。 这个简单的表单仅提供两个编辑框,如果您想提供一个更加用户友好的界面,则可以添加两个ComboBox,并通过枚举可用SQL Server并在SQL Server上检索数据库来填充它们。

The DatabasePrompt form provides a custom class method named Execute that accepts two variable (var) parameters: ServerName and DBName.

DatabasePrompt表单提供了一个名为Execute的自定义类方法 ,该方法接受两个变量(var)参数:ServerName和DBName。

With the "new" data provided by a user (server and database name), we simply call the DBConnect() function again (recursively). Of course, the information is first stored in the Registry (using another custom method: WriteRegistry).

使用用户提供的“新”数据(服务器和数据库名称),我们只需再次(递归)调用DBConnect()函数。 当然,信息首先存储在注册表中(使用另一种自定义方法:WriteRegistry)。

确保DataModule是创建的第一个“表单”! ( Make Sure DataModule Is the First "Form" Created! )

If you try creating this simple project on your own, you might be experiencing Access Violation exceptions when you run the application. By default, the first form added to the application gets to be the MainForm (the first one created). When you add a data module to the application, the data module is added to the list of "auto-create forms" as the form that gets created after the main form.Now, if you try calling any of the Data Module's properties or methods in the OnCreate event of the MainForm, you'll get an Access Violation exception — as the data module is not yet created.To solve this problem, you need to manually change the created order of the data module — and set it to be the first form that gets created by the application (either using Project-Properties dialog or by editing the Projects source file).

如果尝试自己创建此简单项目,则在运行应用程序时可能遇到访问冲突异常。 默认情况下,添加到应用程序的第一个表单将成为MainForm(创建的第一个表单)。 将数据模块添加到应用程序时,该数据模块将作为在主表单之后创建的表单添加到“自动创建表单”列表中。现在,如果您尝试调用任何数据模块的属性或方法在MainForm的OnCreate事件中,您将获得一个Access Violation异常-由于尚未创建数据模块。要解决此问题,您需要手动更改数据模块的创建顺序-并将其设置为由应用程序创建的第一个表单(使用“项目属性”对话框或通过编辑“ 项目”源文件 )。

Since the data module is created before the main form, you can safely call the methods from the data module in the MainForm's OnCreate event.

由于数据模块是在主窗体之前创建的,因此您可以安全地从MainForm的OnCreate事件中的数据模块中调用方法。

翻译自: https://www.thoughtco.com/constructing-the-database-connection-string-dynamically-4092541

数据库连接字符串中非法字符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值