Database connections
Opening a connection
type db = {
}
Login information for a database. Use
None
for default values
val defaults : db
Login information using all defaults
type protocol =
| PROTOCOL_DEFAULT
| PROTOCOL_TCP
| PROTOCOL_SOCKET
| PROTOCOL_PIPE
| PROTOCOL_MEMORY
type db_option =
| OPT_COMPRESS
| OPT_NAMED_PIPE
| OPT_LOCAL_INFILE of bool
| OPT_RECONNECT of bool
| OPT_SSL_VERIFY_SERVER_CERT of int
| REPORT_DATA_TRUNCATION of bool
| OPT_PROTOCOL of protocol
| OPT_CONNECT_TIMEOUT of int
Connect timeout in seconds
| OPT_READ_TIMEOUT of int
The timeout in seconds for attempts to read from the server. Each attempt uses this timeout value and there are retries if necessary, so the total effective timeout value is three times the option value.
| OPT_WRITE_TIMEOUT of int
The timeout in seconds for attempts to write to the server. Each attempt uses this timeout value and there are net_retry_count retries if necessary, so the total effective timeout value is net_retry_count times the option value.
| INIT_COMMAND of string
| READ_DEFAULT_FILE of string
Read options from the named option file instead of from my.cnf.
| READ_DEFAULT_GROUP of string
Read options from the named group
| SET_CHARSET_DIR of string
The path name to the directory that contains character set definition files.
| SET_CHARSET_NAME of string
The name of the character set to use as the default character set.
| SHARED_MEMORY_BASE_NAME of string
The name of the shared-memory object for communication to the server on Windows, if the server supports shared-memory connections
| OPT_FOUND_ROWS
Return the number of found (matched) rows, not the number of changed rows.
val init : unit -> unit
Initialize library (in particular initializes default character set for
escape
NB it is recommended to always usereal_escape
) NB init is called automatically when db handle is created
val connect : ?options:db_option list -> db -> dbd
connect ?options db
connects to the databasedb
and returns a handle for further use- parameter options
connection specific options, default empty list
val quick_connect : ?options:db_option list -> ?host:string -> ?database:string -> ?port:int -> ?password:string -> ?user:string -> ?socket:string -> unit -> dbd
Shortcut for connecting to a database with mostly default field values
Altering a connection
val set_charset : dbd -> string -> unit
set_charset dbd charset
sets the current character set fordbd
(akaSET NAMES
). It is strongly recommended to set the charset explicitly after connecting to database, using this function. Available character sets are stored inINFORMATION_SCHEMA.CHARACTER_SETS
table (SHOW CHARACTER SET
).
val change_user : dbd -> db -> unit
change_user dbd db
tries to change the current user and database. The host and port fields of db are ignored.
val quick_change : ?user:string -> ?password:string -> ?database:string -> dbd -> unit
Another shortcut
val select_db : dbd -> string -> unit
select_db
switches to a new db, using the current user and password.
val disconnect : dbd -> unit
disconnect dbd
releases a database connectiondbd
. The handledbd
becomes invalid
val ping : dbd -> unit
ping dbd
makes sure the connection to the server is up, and re-establishes it if needed.
Information about a connection
val list_dbs : dbd -> ?pat:string -> unit -> string array option
list_db
Return a list of all visible databases on the current server
val host_info : dbd -> string
Return information about the server connection
val server_info : dbd -> string
Return the MySQL server version
val proto_info : dbd -> int
Return the protocol version being used
Errors
exception Error of string
When most of the API functions fail, they raise this exception with a description of the failure.
type error_code =
Possible error codes from a failed operation that doesn't throw an exception
type status =
| StatusOK
The query was successful
| StatusEmpty
The query was successful, but found no results
| StatusError of error_code
There was some problem with the query
The status of a query
val errno : dbd -> error_code
errno dbd
returns the error_code for the last action ondbd
. Useful when you know there's an error, to avoid an extra layer of matching instatus
val errmsg : dbd -> string option
errmsg dbd
returns an error message in case the last operation ondbd
failed
Queries
Making a query
val exec : dbd -> string -> result
exec dbd str
executes a SQL statement and returns a handle to obtain the result. Checkstatus
for errors!
Getting the results of a query
val fetch : result -> string option array option
fetch result
returns the next row from a result asSome a
orNone
in case there is no next result. The arraya
contains the values from the current row, where NULL values are denoted byNone
. Usecolumn
to fetch single values by field name instead of by position
val to_row : result -> int64 -> unit
to_row result row
sets the current row.- raises Invalid_argument
if the row is out of range.
val size : result -> int64
size result
returns the size of the actual result set (number of rows)
val iter : result -> f:(string option array -> unit) -> unit
val iter_col : result -> key:string -> f:(string option -> unit) -> unit
val iter_cols : result -> key:string array -> f:(string option array -> unit) -> unit
val map : result -> f:(string option array -> 'a) -> 'a list
val map_col : result -> key:string -> f:(string option -> 'a) -> 'a list
val map_cols : result -> key:string array -> f:(string option array -> 'a) -> 'a list
val column : result -> key:string -> row:string option array -> string option
Returns one field of a result row based on column name.
Metainformation about a result set
type dbty =
| IntTy
| FloatTy
| StringTy
| SetTy
| EnumTy
| DateTimeTy
| DateTy
| TimeTy
| YearTy
| TimeStampTy
| UnknownTy
| Int64Ty
| BlobTy
| DecimalTy
The type of a database field. Each of these represents one or more MySQL data types.
type field = {
name : string;
Name of the field
table : string option;
Table name, or None if a constructed field
def : string option;
Default value of the field
ty : dbty;
The type of data stored in the field
max_length : int;
Maximum width of field for the result set
flags : int;
Flags set
decimals : int;
Number of decimals for numeric fields
}
The type that describes a field of a table or result
val pretty_type : dbty -> string
Turn a field-type type into a string for printing
val affected : dbd -> int64
affected result
returns the number of rows changed by the last UPDATE, or deleted by the last DELETE, or added by the last INSERT, or the number of rows returned by the last SELECT
val insert_id : dbd -> int64
insert_id result
returns the ID generated by the last INSERT query in a table with an AUTO_INCREMENT column. See the MySQL documentation for caveats.
val fields : result -> int
fields result
returns the number of fields in a row
val names : result -> string array
names result
returns an array of the field names for the current result
val types : result -> dbty array
types result
returns an array with the MySQL types of the current result
val fetch_field_dir : result -> int -> field option
Returns information on a specific field, with the first field numbered 0
Working with MySQL data types
val escape : string -> string
escape str
returns the same string asstr
in MySQL syntax with special characters quoted to not confuse the MySQL parser.- deprecated
This function poses a security risk (doesn't take into consideration the character set of the current connection and may allow SQL injection pass through). Use
real_escape
instead.
val real_escape : dbd -> string -> string
real_escape dbd str
returnsstr
encoded to an escaped SQL string according to the current character set ofdbd
val decimal2ml : string -> string
val int322ml : string -> int32
val nativeint2ml : string -> nativeint
val int642ml : string -> int64
val float2ml : string -> float
Use for MySQL FLOAT, DOUBLE and REAL types
val set2ml : string -> string list
val datetime2ml : string -> int * int * int * int * int * int
val date2ml : string -> int * int * int
val time2ml : string -> int * int * int
val year2ml : string -> int
val timestamp2ml : string -> int * int * int * int * int * int
val opt : ('a -> 'b) -> 'a option -> 'b option
opt f v
appliesf
to optional valuev
. Use this to fetch data of known type from database fields which might be NULL:opt int2ml str
val not_null : ('a -> 'b) -> 'a option -> 'b
not_null f v
appliesf
toSome v
. Use this to fetch data of known type from database fields which never can be NULL:not_null int2ml str
val ml2rstr : dbd -> string -> string
val ml2blob : string -> string
val ml2rblob : dbd -> string -> string
val ml2int : int -> string
val ml2decimal : string -> string
val ml322int : int32 -> string
val ml642int : int64 -> string
val mlnative2int : nativeint -> string
val ml2float : float -> string
val ml2enum : string -> string
val ml2renum : dbd -> string -> string
val ml2set : string list -> string
val ml2rset : dbd -> string list -> string
val ml2datetime : (int * int * int * int * int * int) -> string
val ml2datetimel : year:int -> month:int -> day:int -> hour:int -> min:int -> sec:int -> string
val ml2date : (int * int * int) -> string
val ml2datel : year:int -> month:int -> day:int -> string
val ml2time : (int * int * int) -> string
val ml2timel : hour:int -> min:int -> sec:int -> string
val ml2year : int -> string
val ml2timestamp : (int * int * int * int * int * int) -> string
val ml2timestampl : year:int -> month:int -> day:int -> hour:int -> min:int -> sec:int -> string
val values : string list -> string
values vs
takes a list of strings and returns a string "(a,b,c ..)" where values are separated by comma and the whole list is enclosed into parentheses. This is useful to construct SQL `insert ... values ( .. )' statements
Prepared statements
module Prepared : sig ... end
Prepared statements with parameters. Consult the MySQL manual for detailed description and possible problems.