简体   繁体   中英

Connect Delphi to SQL database

I'm using Microsoft SQL Server R2 Express to create databases.

When I try to connect to a database using delphi, I have to use this Connection string :

ADOConnection1.ConnectionString := 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=db_formation;Data Source=EVILKID-pc\evilkid;';

where "EVILKID-PC\\evilkid" is the name of my pc,在此处输入图片说明

As you can seem this will only work on my PC. What should I do to make it connect to localhost? I have tried changing the "Data Source" to "localhost" but it would not connect and I would get:

[DBNETLIN][ConnectionOpen(Connect()).]SQL Server does not exist or access denied

Any idea where the problem is?

即使您的实例位于 localhost 上,它仍然是您需要在连接字符串中指定的命名实例:

ADOConnection1.ConnectionString := '... Data Source=localhost\evilkid;';

Couple ways you could get around this. As Michael said, use a config file. Other possibles are use a DSN to access the DB. If it's always localhost/machinename you could retrieve the machine name using any number of methods. I use TtvAPIThing in some older projects and JEDI has a system info component to make accessing these easier.

I would create a UDL file (Connection.UDL) in the local app data path on your PC and let the connection string in the application use it

Var
  plainAppName : String;
  appDataPath : String;

Begin
  plainAppName := ChangeFileExt(ExtractFilePath(ParamStr(0)),'.EXE','');
  appDataPath := IncludeTrailingBackslash(GetSpecialFolderLocation(CSIDL_APPDATA))+plainAppName+'\';
  ADOConnection.Connectionstring := 'FILE NAME = '+appDataPath+'Connection.UDL';

And the Connection.UDL contains

[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=YourPC\InstanceName

in fact, it could be empty. However, you (or the customer) doubleclicks the file, and the oleDB connection dialog opens. now set the server, instance, login credetionals, test the connection and save.

done.

Your app will open the file (well, the ADOConnection will) and you're safe.

Another more generic approach is to simply store the IP/name of the server pc in a INI file and substitute it in the code

CONST
  adoStr = 'Provider=SQLOLEDB.1;Integrated Security=SSPI;'
          +'Persist Security Info=False;Initial Catalog=test;'
          +'Data Source=%s';

ADOConnection.ConnectionString := Format(adoStr,[TheIPOrNameOfThePC]);
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM