MCPConnection


Inherits From:
NSObject
Declared In:
MCPConnection.h


Class Description

$Id: MCPConnection.m,v 1.5 2004/08/04 23:24:06 sergecohen Exp $ $Author: sergecohen $

This class is used to keep a connection with a MySQL server, it correspond to the MYSQL structure of the C API, or the database handle of the PERL DBI/DBD interface.

You have to start any work on a MySQL server by getting a working MCPConnection object.

Most likely you will use this kind of code:

    
    MCPConnection *theConnec = [MCPConnection alloc];
    MCPResult *theRes;
    
    theConnec = [theConnec initToHost:@"albert.com" withLogin:@"toto" password:@"albert" usingPort:0];
    [theConnec selectDB:@"db1"];
    theRes = [theConnec queryString:@"select * from table1"];
    ...
    

NOTE Failing to properly release your MCPConnection(s) object might cause a MySQL crash!!! (recovered if the server was started using mysqld_safe).


Global Variables

Synopsis:

const unsigned int kMCPConnectionDefaultOption;
const char *kMCPConnectionDefaultSocket;
const unsigned int kMCPConnectionNotInited;


Instance Variables

MYSQL *mConnection;
BOOL mConnected;
NSStringEncoding mEncoding;
unsigned int mConnectionFlags;

mConnectionThe inited MySQL connection
mConnectedReflect the fact that the connection is already in place or not
mEncodingThe encoding used by MySQL server, to ISO-1 default
mConnectionFlagsThe flags to be used for the connection to the database.


Method Types

Getting default of MySQL
+ getMySQLLocales
+ encodingForMySQLEncoding:
+ defaultMySQLEncoding
Class maintenance
+ initialize
Initialisation
- init
- initToHost:withLogin:password:usingPort:
- initToSocket:withLogin:password:
- setConnectionOption:toValue:
- connectWithLogin:password:host:port:socket:
- selectDB:
Errors information
- getLastErrorMessage
- getLastErrorID
- isConnected
- checkConnection
Queries
- prepareBinaryData:
- prepareString:
- quoteObject:
- queryString:
- affectedRows
- insertId
Getting description of the database structure
- listDBs
- listDBsLike:
- listTables
- listTablesLike:
- listTablesFromDB:like:
- listFieldsFromTable:
- listFieldsFromTable:like:
Server information and control
- clientInfo
- hostInfo
- serverInfo
- protoInfo
- listProcesses
- killProcess:
Disconnection
- disconnect
- dealloc
String encoding concerns (c string type to NSString). It's unlikely that users of the framework needs to use these methods which are used internally
- setEncoding:
- encoding
- cStringFromString:
- stringWithCString:
Text data convertion to string
- stringWithText:


Class Methods

defaultMySQLEncoding

+ (NSStringEncoding)defaultMySQLEncoding

Returns the default charset of the library mysqlclient used.


encodingForMySQLEncoding:

+ (NSStringEncoding)encodingForMySQLEncoding:(const char *)mysqlEncoding

Gets a proper NSStringEncoding according to the given MySQL charset.

MySQL 4.0 offers this charsets: big5 cp1251 cp1257 croat czech danish dec8 dos estonia euc_kr gb2312 gbk german1 greek hebrew hp8 hungarian koi8_ru koi8_ukr latin1 latin1_de latin2 latin5 sjis swe7 tis620 ujis usa7 win1250 win1251ukr

WARNING : incomplete implementation. Please, send your fixes.


getMySQLLocales

+ (NSDictionary *)getMySQLLocales

Gets a proper Locale dictionary to use formater to parse strings from MySQL. For example strings representing dates should give a proper Locales for use with methods such as NSDate::dateWithNaturalLanguageString: locales:


initialize

+ (void)initialize

Initialize the class version to 2.3.1


Instance Methods

affectedRows

- (my_ulonglong)affectedRows

Returns the number of affected rows by the last query.


cStringFromString:

- (const char *)cStringFromString:(NSString *)theString

For internal use only. Transforms a NSString to a C type string (ending with \0) using the character set from the MCPConnection. Lossy conversions are enabled.


checkConnection

- (BOOL)checkConnection

Checks if the connection to the server is still on. If not, tries to reconnect (changing no parameters from the MYSQL pointer). This method just uses mysql_ping().


clientInfo

- (NSString *)clientInfo

Returns a string giving the client library version.


connectWithLogin:password:host:port:socket:

- (BOOL)connectWithLogin:(NSString *)login password:(NSString *)pass host:(NSString *)host port:(int)port socket:(NSString *)socket

The method used by initToHost:withLogin:password:usingPort: and initToSocket:withLogin:password:. Same information and use of the parameters:

- login is the user name - pass is the password corresponding to the user name - host is the hostname or IP adress - port is the TCP port to use to connect. If port = 0, uses the default port from mysql.h - socket is the path to the socket (for the localhost)

The socket is used if the host is set to @"localhost", to an empty or a nil string For the moment the implementation might not be safe if you have a nil pointer to one of the NSString* variables (underestand: I don't know what the result will be).


dealloc

- (void)dealloc

The standard deallocation method for MCPConnection objects.


disconnect

- (void)disconnect

Disconnects a connected MCPConnection object; used by dealloc: method.


encoding

- (NSStringEncoding)encoding

Gets the encoding for the connection


getLastErrorID

- (unsigned int)getLastErrorID

Returns the ErrorID of the last MySQL error on the connection.


getLastErrorMessage

- (NSString *)getLastErrorMessage

Returns a string with the last MySQL error message on the connection.


hostInfo

- (NSString *)hostInfo

Returns a string giving information on the host of the DB server.


init

- (id)init

Initialise a MySQLConnection without making a connection, most likely useless, except with setConnectionOption:withArgument:.

Because this method is not making a connection to any MySQL server, it can not know already what the DB server encoding will be, hence the encoding is set to some default (at present this is NSISOLatin1StringEncoding). Obviously this is reset to a proper value as soon as a DB connection is performed.

I AM CURRENTLY NOT TESTING THIS METHOD, so it is likely to be buggy... I'd be SUPER happy to ear/read your feed-back on this.


initToHost:withLogin:password:usingPort:

- (id)initToHost:(NSString *)host withLogin:(NSString *)login password:(NSString *)pass usingPort:(int)port

Initialise a connection using a TCP/IP connection with the given parameters (except if host is set to localhost, in which case uses the default)

- host is the hostname or IP adress - login is the user name - pass is the password corresponding to the user name - port is the TCP port to use to connect. If port = 0, uses the default port from mysql.h


initToSocket:withLogin:password:

- (id)initToSocket:(NSString *)socket withLogin:(NSString *)login password:(NSString *)pass

Initialise a connection using a unix socket with the given parameters

- socket is the path to the socket - login is the user name - pass is the password corresponding to the user name


insertId

- (my_ulonglong)insertId

If the last query was an insert in a table having a autoindex column, returns the id (autoindexed field) of the last row inserted.


isConnected

- (BOOL)isConnected

Returns YES if the MCPConnection is connected to a DB, NO otherwise.


killProcess:

- (BOOL)killProcess:(unsigned long)pid

Kills the process with the given pid. The users needs the Process_priv privilege.


listDBs

- (MCPResult *)listDBs

Just a fast wrapper for the more complex listDBsWithPattern: method.


listDBsLike:

- (MCPResult *)listDBsLike:(NSString *)dbsName

Returns a list of database which name correspond to the SQL regular expression in 'pattern'. The comparison is done with wild card extension : % and _. The result should correspond to the queryString:@"SHOW databases [LIKE wild]"; but implemented with mysql_list_dbs. If an empty string or nil is passed as pattern, all databases will be shown.


listFieldsFromTable:

- (MCPResult *)listFieldsFromTable:(NSString *)tableName

Just a fast wrapper for the more complex list listFieldsWithPattern:forTable: method.


listFieldsFromTable:like:

- (MCPResult *)listFieldsFromTable:(NSString *)tableName like:(NSString *)fieldsName

Show all the fields of the table tableName which name correspond to pattern (with wild card expansion : %,_). Indeed, and as recommanded from mysql reference, this method is NOT using mysql_list_fields but the queryString: method. If an empty string or nil is passed as fieldsName, all fields (of tableName) will be returned.


listProcesses

- (MCPResult *)listProcesses

Lists active process


listTables

- (MCPResult *)listTables

Make sure a DB is selected (with selectDB: method) first.


listTablesFromDB:like:

- (MCPResult *)listTablesFromDB:(NSString *)dbName like:(NSString *)tablesName

List tables in DB specified by dbName and corresponding to pattern. This method indeed issues a SHOW TABLES FROM dbName LIKE ... query to the server. This is done this way to make sure the selected DB is not changed by this method.


listTablesLike:

- (MCPResult *)listTablesLike:(NSString *)tablesName

From within a database, give back the list of table which name correspond to tablesName (with wild card %, _ extension). Correspond to queryString:@"SHOW tables [LIKE wild]"; uses mysql_list_tables function. If an empty string or nil is passed as tablesName, all tables will be shown. WARNING: produce an error if no databases are selected (with selectDB: for example).


prepareBinaryData:

- (NSString *)prepareBinaryData:(NSData *)theData

Takes a NSData object and transform it in a proper string for sending to the server in between quotes.


prepareString:

- (NSString *)prepareString:(NSString *)theString

Takes a string and escape any special character (like single quote : ') so that the string can be used directly in a query.


protoInfo

- (NSNumber *)protoInfo

Returns the number of the protocole used to transfer info from server to client


queryString:

- (MCPResult *)queryString:(NSString *)query

Takes a query string and return an MCPResult object holding the result of the query. The returned MCPResult is not retained, the client is responsible for that (it's autoreleased before being returned). If no field are present in the result (like in an insert query), will return nil (difference from previous version implementation). Though, if their is at least one field the result will be non nil (even if no row are selected).

Note that if you want to use this method with binary data (in the query), you should use prepareBinaryData: to include the binary data in the query string. Also if you want to include in your query a string containing any special character (\, ', " ...) then you should use prepareString.


quoteObject:

- (NSString *)quoteObject:(id)theObject

Use the class of the theObject to know how it should be prepared for usage with the database. If theObject is a string, this method will put single quotes to both its side and escape any necessary character using prepareString: method. If theObject is NSData, the prepareBinaryData: method will be used instead. For NSNumber object, the number is just quoted, for calendar dates, the calendar date is formatted in the preferred format for the database.


selectDB:

- (BOOL)selectDB:(NSString *)dbName

Selects a database to work with. The MCPConnection object needs to be properly inited and connected to a server. If a connection is not yet set or the selection of the database didn't work, returns NO. Returns YES in normal cases where the database is properly selected.

So far, if dbName is a nil pointer it will return NO (as if it cannot connect), most likely this will throw an exception in the future.


serverInfo

- (NSString *)serverInfo

Returns a string giving the server version.


setConnectionOption:toValue:

- (BOOL)setConnectionOption:(int)option toValue:(BOOL)value

IMPLEMENTED BUT NOT TESTED!!

This method is to be used for getting special option for a connection, in which case the MCPConnection has to be inited with the init method, then option are selected, finally connection is done using one of the connect methods:

    
    MCPConnection *theConnect = [[MCPConnection alloc] init];
    [theConnect setConnectionOption: option toValue: value];
    [theConnect connectToHost:albert.com withLogin:@"toto" password:@"albert" port:0];
    ....
    


setEncoding:

- (void)setEncoding:(NSStringEncoding)theEncoding

Sets the encoding used by the server for data transfert. Used to make sure the output of the query result is ok even for non-ascii characters The character set (encoding) used by the db is passed to the MCPConnection object upon connection, so most likely the encoding (from -encoding) method is already the proper one. That is to say : It's unlikely you will need to call this method directly, and if ever you use it, do it at your own risks.


stringWithCString:

- (NSString *)stringWithCString:(const char *)theCString

Returns a NSString from a C style string encoded with the character set of theMCPConnection.


stringWithText:

- (NSString *)stringWithText:(NSData *)theTextData

Use the string encoding to convert the returned NSData to a string (for a Text field)


Version 1.3 Copyright ©2004 by Serge Cohen. All Rights Reserved. Mon Aug 09 11:00:27 2004