1. Use Delphi to connect to the MySQL database. Two methods are recommended: dbexpress and ODBC. Dbexpress is highly efficient, but it is troublesome for local client datasets. ODBC is very common. If ODBC is used as the database access layer, it is easy to switch back-end databases, and the Code does not need to be modified. Let's assume that we use ODBC to connect to the MySQL database. First, we need to download the ODBC driver of MySQL. Then we can download it from the official MySQL website and install it.
2. In a program, ODBC is automatically configured according to the user's configuration, rather than opening the ODBC Configuration window for manual configuration. ODBC configuration information is generally written in the Registry: HKEY_LOCAL_MACHINE/software/ODBC. INI/ODBC data sources. We can establish an ODBC connection by writing the registry, but it is still difficult to operate the Registry. For simplicity, we use the configuration API function: sqlconfigdatasource provided by the ODBC driver.
First, import the sqlconfigdatasource declaration in the Delphi unit:
Function sqlconfigdatasource (hwndparent: integer; frequest: integer; lpszdriverstring: string; lpszattributes: string): integer; stdcall; External 'odbccp32. dll ';
Execute the sqlconfigdatasource function where ODBC needs to be configured:
Sqlconfigdatasource (0, 4, 'mysql ODBC 3.51 driver ',
'Dsn = yourdsnname' + CHR (0) +
'Database = yourdatabase' + CHR (0) +
'Server = 192.168.10.36 '+ CHR (0) +
'Uid = root' + CHR (0) +
'Pwd = yourpwd' + CHR (0 ));
The first parameter is fixed to 0.
The second parameter is the configuration operation type:
# Define odbc_add_dsn 1
# Define odbc_config_dsn 2
# Define odbc_remove_dsn 3
# Define odbc_add_sys_dsn 4
# Define odbc_config_sys_dsn 5
# Define odbc_remove_sys_dsn 6
# Define odbc_remove_default_dsn 7
The third parameter is the name of the database driver.
The fourth parameter is the configuration attribute string. Each attribute must be separated by '/0'. You can use CHR (0) in Delphi ).
After execution, an ODBC data source named yourdsnname is created. You can call the preceding function repeatedly without worrying that multiple ODBC data sources with the same name will be created.
ODBC data source.