RU/dbConnect

From Multi Theft Auto: Wiki
Revision as of 00:27, 27 December 2014 by Strix (talk | contribs)
Jump to navigation Jump to search

Эта функция открывает подключение к базе данных и возвращает элемент, который может быть использован с dbQuery. Для отключения используйте destroyElement.

[[{{{image}}}|link=|]] Примечание: Connecting and disconnecting many times can have a performance impact on the server. For optimal performance it is recommended that you use dbConnect only once when the resource starts, and share the connection element with the whole script.
[[{{{image}}}|link=|]] Примечание: dbConnect на Linux MySQL требует libmysqlclient.so.15 (для MTA 1.3), или libmysqlclient.so.16 (для MTA 1.4)

Синтаксис

element dbConnect ( string databaseType, string host [, string username = "", string password = "", string options = "" ] )

Синтаксис ООП Помогите! Я не понимаю, что это!

Метод: Connection(...)

Обязательные параметры

  • databaseType: Тип базы данных. Может быть sqlite или mysql
  • host: The target to connect to. The format of this depends on the database type.
    • Для SQLite it is a filepath to a SQLite database file. If the filepath starts with ":/" then the server's global databases directory is used. The file will be created if it does not exist.
    • Для MySQL it is a list of key=value pairs separated by semicolons. Supported keys are:
      • dbname: Name of the database to use e.g. dbname=test
      • host: Host address e.g. host=127.0.0.1
      • port: Host port e.g. port=1234 (optional, defaults to standard MySQL port if not used)
      • unix_socket: Unix socket or named pipe to use (optional, thankgoodness)

Необязательные параметры

  • username: Обычно требуется для MySQL, игнорируется для SQLite
  • password: Обычно требуется для MySQL, игнорируется для SQLite
  • options : List of key=value pairs separated by semicolons. Supported keys are:
    • share which can be set to 0 or 1. (Default value for SQLite is "share=1", for MySQL is "share=0"). When set to 1, the connection is shared and will be used by other calls to dbConnect with the same host string. This is usually a good thing for SQLite connections, but not so good for MySQL unless care is taken.
    • batch which can be set to 0 or 1. (Default is "batch=1"). When set to 1, queries called in the same frame are automatically batched together which can significantly speed up inserts/updates. The downside is you lose control of the feature that is used to achieve batching (For SQLite it is transactions, for MySQL it is autocommit mode). Therefore, if you use transactions, lock tables or control autocommit yourself, you may want to disable this feature.
    • autoreconnect which can be set to 0 or 1. (Default value "autoreconnect=1"). When set to 1, dropped connections will automatically be reconnected. Note that session variables, user variables, table locks and temporary tables will be reset because of the reconnection. So if you use these fancy features, you will need to turn autoreconnect off and cope with dropped connections some other way.
    • log which can be set to 0 or 1. (Default value "log=1"). When set to 0, activity from this connection will not be recorded in the database debug log file.
    • tag (Default value "tag=script"). A string which helps identify activity from this connection in the database debug log file.
    • suppress A comma separated list of error codes to ignore. (eg. "suppress=1062,1169").
    • charset If you want to communicate with the server using a character set different from the default, you'll need to indicate which one. (eg. "charset=utf8"). (used only in MySQL)

Возвращает

Возвращает элемент подключения к базе данных, если проблем нет, в противном случае false.

Пример

This example opens a connection to a SQLite database file in the current resource

test_db = dbConnect( "sqlite", "file.db" )

This example opens a connection to a SQLite database file in another resource

test_db = dbConnect( "sqlite", ":resname/file.db" )

This example opens a connection to a SQLite database file in the global databases directory

test_db = dbConnect( "sqlite", ":/file.db" )

This example opens a connection to a SQLite database file in a sub directory of the global databases directory

test_db = dbConnect( "sqlite", ":/example/sub/dir/file.db" )

This example opens a connection to a MySQL database called 'frank' at server ip 1.2.3.4 and allows the connection to be shared. Note that changing the database or other connection dependent settings affect all connections that are shared.

test_db = dbConnect( "mysql", "dbname=frank;host=1.2.3.4", "username", "password", "share=1" )

This example opens a connection to a SQLite database is disallows sharing of the connection

test_db = dbConnect( "sqlite", "file.db", "", "", "share=0" )

Требования

Минимально поддерживаемый сервер 1.1.1-9.03328
Минимально поддерживаемый клиент n/a

Примечание: Использование этой функции требует указания минимальной версии в разделе <min_mta_version> meta.xml ресурса. Пример: <min_mta_version server="1.1.1-9.03328" />


Список изменений

Version Description
1.3.1-9.04817 Добавлены опции 'log', 'tag' и 'suppress'
1.3.5-9.06386 Добавлена опция 'charset'

Смотрите также

Template:RU/Registry functions