Qt 4.8
Public Functions | Protected Slots | Protected Functions | Private Functions | Properties | Friends | List of all members
QMYSQLDriver Class Reference

#include <qsql_mysql.h>

Inheritance diagram for QMYSQLDriver:
QSqlDriver QObject

Public Functions

void close ()
 Derived classes must reimplement this pure virtual function in order to close the database connection. More...
 
QSqlResultcreateResult () const
 Creates an empty SQL result on the database. More...
 
QString escapeIdentifier (const QString &identifier, IdentifierType type) const
 Returns the identifier escaped according to the database rules. More...
 
QString formatValue (const QSqlField &field, bool trimStrings) const
 Returns a string representation of the field value for the database. More...
 
QVariant handle () const
 Returns the low-level database handle wrapped in a QVariant or an invalid variant if there is no handle. More...
 
bool hasFeature (DriverFeature f) const
 Returns true if the driver supports feature feature; otherwise returns false. More...
 
bool open (const QString &db, const QString &user, const QString &password, const QString &host, int port, const QString &connOpts)
 Derived classes must reimplement this pure virtual function to open a database connection on database db, using user name user, password password, host host, port port and connection options options. More...
 
QSqlIndex primaryIndex (const QString &tablename) const
 Returns the primary index for table tableName. More...
 
 QMYSQLDriver (QObject *parent=0)
 
 QMYSQLDriver (MYSQL *con, QObject *parent=0)
 Create a driver instance with the open connection handle, con. More...
 
QSqlRecord record (const QString &tablename) const
 Returns a QSqlRecord populated with the names of the fields in table tableName. More...
 
QStringList tables (QSql::TableType) const
 Returns a list of the names of the tables in the database. More...
 
 ~QMYSQLDriver ()
 
- Public Functions inherited from QSqlDriver
bool isIdentifierEscaped (const QString &identifier, IdentifierType type) const
 Returns whether identifier is escaped according to the database rules. More...
 
virtual bool isOpen () const
 Returns true if the database connection is open; otherwise returns false. More...
 
bool isOpenError () const
 Returns true if the there was an error opening the database connection; otherwise returns false. More...
 
QSqlError lastError () const
 Returns a QSqlError object which contains information about the last error that occurred on the database. More...
 
QSql::NumericalPrecisionPolicy numericalPrecisionPolicy () const
 Returns the current default precision policy for the database connection. More...
 
 QSqlDriver (QObject *parent=0)
 Constructs a new driver with the given parent. More...
 
void setNumericalPrecisionPolicy (QSql::NumericalPrecisionPolicy precisionPolicy)
 Sets the default numerical precision policy used by queries created by this driver to precisionPolicy. More...
 
virtual QString sqlStatement (StatementType type, const QString &tableName, const QSqlRecord &rec, bool preparedStatement) const
 Returns a SQL statement of type type for the table tableName with the values from rec. More...
 
QString stripDelimiters (const QString &identifier, IdentifierType type) const
 Returns the identifier with the leading and trailing delimiters removed, identifier can either be a table name or field name, dependent on type. More...
 
QStringList subscribedToNotifications () const
 Returns a list of the names of the event notifications that are currently subscribed to. More...
 
bool subscribeToNotification (const QString &name)
 This function is called to subscribe to event notifications from the database. More...
 
bool unsubscribeFromNotification (const QString &name)
 This function is called to unsubscribe from event notifications from the database. More...
 
 ~QSqlDriver ()
 Destroys the object and frees any allocated resources. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Protected Slots

bool isIdentifierEscapedImplementation (const QString &identifier, IdentifierType type) const
 
- Protected Slots inherited from QSqlDriver
bool isIdentifierEscapedImplementation (const QString &identifier, IdentifierType type) const
 This slot returns whether identifier is escaped according to the database rules. More...
 
QString stripDelimitersImplementation (const QString &identifier, IdentifierType type) const
 This slot returns identifier with the leading and trailing delimiters removed, identifier can either be a tablename or field name, dependent on type. More...
 
QStringList subscribedToNotificationsImplementation () const
 Returns a list of the names of the event notifications that are currently subscribed to. More...
 
bool subscribeToNotificationImplementation (const QString &name)
 This slot is called to subscribe to event notifications from the database. More...
 
bool unsubscribeFromNotificationImplementation (const QString &name)
 This slot is called to unsubscribe from event notifications from the database. More...
 

Protected Functions

bool beginTransaction ()
 This function is called to begin a transaction. More...
 
bool commitTransaction ()
 This function is called to commit a transaction. More...
 
bool rollbackTransaction ()
 This function is called to rollback a transaction. More...
 
- Protected Functions inherited from QSqlDriver
virtual void setLastError (const QSqlError &e)
 This function is used to set the value of the last error, error, that occurred on the database. More...
 
virtual void setOpen (bool o)
 This function sets the open state of the database to open. More...
 
virtual void setOpenError (bool e)
 This function sets the open error state of the database to error. More...
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Private Functions

void init ()
 

Properties

QMYSQLDriverPrivated
 

Friends

class QMYSQLResult
 

Additional Inherited Members

- Public Types inherited from QSqlDriver
enum  DriverFeature {
  Transactions, QuerySize, BLOB, Unicode,
  PreparedQueries, NamedPlaceholders, PositionalPlaceholders, LastInsertId,
  BatchOperations, SimpleLocking, LowPrecisionNumbers, EventNotifications,
  FinishQuery, MultipleResultSets
}
 This enum contains a list of features a driver might support. More...
 
enum  IdentifierType { FieldName, TableName }
 This enum contains a list of SQL identifier types. More...
 
enum  StatementType {
  WhereStatement, SelectStatement, UpdateStatement, InsertStatement,
  DeleteStatement
}
 This enum contains a list of SQL statement (or clause) types the driver can create. More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 
- Signals inherited from QSqlDriver
void notification (const QString &name)
 This signal is emitted when the database posts an event notification that the driver subscribes to. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 
- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

Definition at line 102 of file qsql_mysql.h.

Constructors and Destructors

◆ QMYSQLDriver() [1/2]

QMYSQLDriver::QMYSQLDriver ( QObject parent = 0)
explicit

Definition at line 1123 of file qsql_mysql.cpp.

1124  : QSqlDriver(parent)
1125 {
1126  init();
1127  qLibraryInit();
1128 }
static void qLibraryInit()
QSqlDriver(QObject *parent=0)
Constructs a new driver with the given parent.
Definition: qsqldriver.cpp:112

◆ QMYSQLDriver() [2/2]

QMYSQLDriver::QMYSQLDriver ( MYSQL *  con,
QObject parent = 0 
)
explicit

Create a driver instance with the open connection handle, con.

The instance's parent (owner) is parent.

Definition at line 1135 of file qsql_mysql.cpp.

1136  : QSqlDriver(parent)
1137 {
1138  init();
1139  if (con) {
1140  d->mysql = (MYSQL *) con;
1141 #ifndef QT_NO_TEXTCODEC
1142  d->tc = codec(con);
1143 #endif
1144  setOpen(true);
1145  setOpenError(false);
1146  if (qMySqlConnectionCount == 1)
1147  qMySqlInitHandledByUser = true;
1148  } else {
1149  qLibraryInit();
1150  }
1151 }
virtual void setOpen(bool o)
This function sets the open state of the database to open.
Definition: qsqldriver.cpp:283
static int qMySqlConnectionCount
QTextCodec * tc
Definition: qsql_mysql.cpp:90
virtual void setOpenError(bool e)
This function sets the open error state of the database to error.
Definition: qsqldriver.cpp:297
static QTextCodec * codec(MYSQL *mysql)
Definition: qsql_mysql.cpp:220
static bool qMySqlInitHandledByUser
static void qLibraryInit()
QSqlDriver(QObject *parent=0)
Constructs a new driver with the given parent.
Definition: qsqldriver.cpp:112
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ ~QMYSQLDriver()

QMYSQLDriver::~QMYSQLDriver ( )

Definition at line 1160 of file qsql_mysql.cpp.

1161 {
1164  qLibraryEnd();
1165  delete d;
1166 }
static int qMySqlConnectionCount
static bool qMySqlInitHandledByUser
static void qLibraryEnd()
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

Functions

◆ beginTransaction()

bool QMYSQLDriver::beginTransaction ( )
protectedvirtual

This function is called to begin a transaction.

If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also
commitTransaction(), rollbackTransaction()

Reimplemented from QSqlDriver.

Definition at line 1447 of file qsql_mysql.cpp.

1448 {
1449 #ifndef CLIENT_TRANSACTIONS
1450  return false;
1451 #endif
1452  if (!isOpen()) {
1453  qWarning("QMYSQLDriver::beginTransaction: Database not open");
1454  return false;
1455  }
1456  if (mysql_query(d->mysql, "BEGIN WORK")) {
1457  setLastError(qMakeError(tr("Unable to begin transaction"),
1459  return false;
1460  }
1461  return true;
1462 }
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QMYSQLDriverPrivate *p)
Definition: qsql_mysql.cpp:231
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
Q_CORE_EXPORT void qWarning(const char *,...)
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ close()

void QMYSQLDriver::close ( )
virtual

Derived classes must reimplement this pure virtual function in order to close the database connection.

Return true on success, false on failure.

See also
open(), setOpen()

Implements QSqlDriver.

Definition at line 1336 of file qsql_mysql.cpp.

Referenced by open().

1337 {
1338  if (isOpen()) {
1339 #ifndef QT_NO_THREAD
1340  mysql_thread_end();
1341 #endif
1342  mysql_close(d->mysql);
1343  d->mysql = NULL;
1344  setOpen(false);
1345  setOpenError(false);
1346  }
1347 }
virtual void setOpen(bool o)
This function sets the open state of the database to open.
Definition: qsqldriver.cpp:283
virtual void setOpenError(bool e)
This function sets the open error state of the database to error.
Definition: qsqldriver.cpp:297
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ commitTransaction()

bool QMYSQLDriver::commitTransaction ( )
protectedvirtual

This function is called to commit a transaction.

If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also
beginTransaction(), rollbackTransaction()

Reimplemented from QSqlDriver.

Definition at line 1464 of file qsql_mysql.cpp.

1465 {
1466 #ifndef CLIENT_TRANSACTIONS
1467  return false;
1468 #endif
1469  if (!isOpen()) {
1470  qWarning("QMYSQLDriver::commitTransaction: Database not open");
1471  return false;
1472  }
1473  if (mysql_query(d->mysql, "COMMIT")) {
1474  setLastError(qMakeError(tr("Unable to commit transaction"),
1476  return false;
1477  }
1478  return true;
1479 }
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QMYSQLDriverPrivate *p)
Definition: qsql_mysql.cpp:231
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
Q_CORE_EXPORT void qWarning(const char *,...)
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ createResult()

QSqlResult * QMYSQLDriver::createResult ( ) const
virtual

Creates an empty SQL result on the database.

Derived classes must reimplement this function and return a QSqlResult object appropriate for their database to the caller.

Implements QSqlDriver.

Definition at line 1349 of file qsql_mysql.cpp.

Referenced by primaryIndex(), and tables().

1350 {
1351  return new QMYSQLResult(this);
1352 }
friend class QMYSQLResult
Definition: qsql_mysql.h:105

◆ escapeIdentifier()

QString QMYSQLDriver::escapeIdentifier ( const QString identifier,
IdentifierType  type 
) const
virtual

Returns the identifier escaped according to the database rules.

identifier can either be a table name or field name, dependent on type.

The default implementation does nothing.

See also
isIdentifierEscaped()

Reimplemented from QSqlDriver.

Definition at line 1532 of file qsql_mysql.cpp.

1533 {
1534  QString res = identifier;
1535  if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('`')) && !identifier.endsWith(QLatin1Char('`')) ) {
1536  res.prepend(QLatin1Char('`')).append(QLatin1Char('`'));
1537  res.replace(QLatin1Char('.'), QLatin1String("`.`"));
1538  }
1539  return res;
1540 }
QString & replace(int i, int len, QChar after)
Definition: qstring.cpp:2005
QString & prepend(QChar c)
Definition: qstring.h:261
bool startsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string starts with s; otherwise returns false.
Definition: qstring.cpp:3734
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
QString & append(QChar c)
Definition: qstring.cpp:1777
bool endsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string ends with s; otherwise returns false.
Definition: qstring.cpp:3796
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ formatValue()

QString QMYSQLDriver::formatValue ( const QSqlField field,
bool  trimStrings 
) const
virtual

Returns a string representation of the field value for the database.

Use the other formatValue() overload instead.

This is used, for example, when constructing INSERT and UPDATE statements.

The default implementation returns the value formatted as a string according to the following rules:

  • If field is character data, the value is returned enclosed in single quotation marks, which is appropriate for many SQL databases. Any embedded single-quote characters are escaped (replaced with two single-quote characters). If trimStrings is true (the default is false), all trailing whitespace is trimmed from the field.

  • If field is date/time data, the value is formatted in ISO format and enclosed in single quotation marks. If the date/time data is invalid, "NULL" is returned.

  • If field is bytearray data, and the driver can edit binary fields, the value is formatted as a hexadecimal string.

  • For any other field type, toString() is called on its value and the result of this is returned.

See also
QVariant::toString()

Reimplemented from QSqlDriver.

Definition at line 1498 of file qsql_mysql.cpp.

1499 {
1500  QString r;
1501  if (field.isNull()) {
1502  r = QLatin1String("NULL");
1503  } else {
1504  switch(field.type()) {
1505  case QVariant::String:
1506  // Escape '\' characters
1507  r = QSqlDriver::formatValue(field, trimStrings);
1508  r.replace(QLatin1String("\\"), QLatin1String("\\\\"));
1509  break;
1510  case QVariant::ByteArray:
1511  if (isOpen()) {
1512  const QByteArray ba = field.value().toByteArray();
1513  // buffer has to be at least length*2+1 bytes
1514  char* buffer = new char[ba.size() * 2 + 1];
1515  int escapedSize = int(mysql_real_escape_string(d->mysql, buffer,
1516  ba.data(), ba.size()));
1517  r.reserve(escapedSize + 3);
1518  r.append(QLatin1Char('\'')).append(toUnicode(d->tc, buffer)).append(QLatin1Char('\''));
1519  delete[] buffer;
1520  break;
1521  } else {
1522  qWarning("QMYSQLDriver::formatValue: Database not open");
1523  }
1524  // fall through
1525  default:
1526  r = QSqlDriver::formatValue(field, trimStrings);
1527  }
1528  }
1529  return r;
1530 }
char * data()
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:429
QTextCodec * tc
Definition: qsql_mysql.cpp:90
QVariant value() const
Returns the value of the field as a QVariant.
Definition: qsqlfield.h:71
QString & replace(int i, int len, QChar after)
Definition: qstring.cpp:2005
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
The QString class provides a Unicode character string.
Definition: qstring.h:83
QByteArray toByteArray() const
Returns the variant as a QByteArray if the variant has type() ByteArray or String (converted using QS...
Definition: qvariant.cpp:2383
void reserve(int size)
Attempts to allocate memory for at least size characters.
Definition: qstring.h:881
Q_CORE_EXPORT void qWarning(const char *,...)
QVariant::Type type() const
Returns the field&#39;s type as stored in the database.
Definition: qsqlfield.cpp:394
static QString toUnicode(QTextCodec *tc, const char *str)
Definition: qsql_mysql.cpp:95
QString & append(QChar c)
Definition: qstring.cpp:1777
bool isNull() const
Returns true if the field&#39;s value is NULL; otherwise returns false.
Definition: qsqlfield.cpp:428
virtual QString formatValue(const QSqlField &field, bool trimStrings=false) const
Returns a string representation of the field value for the database.
Definition: qsqldriver.cpp:597
int size() const
Returns the number of bytes in this byte array.
Definition: qbytearray.h:402
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ handle()

QVariant QMYSQLDriver::handle ( ) const
virtual

Returns the low-level database handle wrapped in a QVariant or an invalid variant if there is no handle.

Warning
Use this with uttermost care and only if you know what you're doing.
The handle returned here can become a stale pointer if the connection is modified (for example, if you close the connection).
The handle can be NULL if the connection is not open yet.

The handle returned here is database-dependent, you should query the type name of the variant before accessing it.

This example retrieves the handle for a connection to sqlite:

QSqlDatabase db = ...;
QVariant v = db.driver()->handle();
if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*") == 0) {
// v.data() returns a pointer to the handle
sqlite3 *handle = *static_cast<sqlite3 **>(v.data());
if (handle != 0) { // check that it is not NULL
...
}
}

This snippet returns the handle for PostgreSQL or MySQL:

if (qstrcmp(v.typeName(), "PGconn*") == 0) {
PGconn *handle = *static_cast<PGconn **>(v.data());
if (handle != 0) ...
}
if (qstrcmp(v.typeName(), "MYSQL*") == 0) {
MYSQL *handle = *static_cast<MYSQL **>(v.data());
if (handle != 0) ...
}
See also
QSqlResult::handle()

Reimplemented from QSqlDriver.

Definition at line 1442 of file qsql_mysql.cpp.

1443 {
1444  return QVariant::fromValue(d->mysql);
1445 }
static QVariant fromValue(const T &value)
Returns a QVariant containing a copy of value.
Definition: qvariant.h:336
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ hasFeature()

bool QMYSQLDriver::hasFeature ( DriverFeature  feature) const
virtual

Returns true if the driver supports feature feature; otherwise returns false.

Note that some databases need to be open() before this can be determined.

See also
DriverFeature

Implements QSqlDriver.

Definition at line 1168 of file qsql_mysql.cpp.

1169 {
1170  switch (f) {
1171  case Transactions:
1172 // CLIENT_TRANSACTION should be defined in all recent mysql client libs > 3.23.34
1173 #ifdef CLIENT_TRANSACTIONS
1174  if (d->mysql) {
1175  if ((d->mysql->server_capabilities & CLIENT_TRANSACTIONS) == CLIENT_TRANSACTIONS)
1176  return true;
1177  }
1178 #endif
1179  return false;
1180  case NamedPlaceholders:
1181  case BatchOperations:
1182  case SimpleLocking:
1183  case EventNotifications:
1184  case FinishQuery:
1185  return false;
1186  case QuerySize:
1187  case BLOB:
1188  case LastInsertId:
1189  case Unicode:
1190  case LowPrecisionNumbers:
1191  return true;
1192  case PreparedQueries:
1194 #if MYSQL_VERSION_ID >= 40108
1195  return d->preparedQuerysEnabled;
1196 #else
1197  return false;
1198 #endif
1199  case MultipleResultSets:
1200 #if MYSQL_VERSION_ID >= 40100
1201  return true;
1202 #else
1203  return false;
1204 #endif
1205  }
1206  return false;
1207 }
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ init()

void QMYSQLDriver::init ( )
private

Definition at line 1153 of file qsql_mysql.cpp.

Referenced by QMYSQLDriver().

1154 {
1155  d = new QMYSQLDriverPrivate();
1156  d->mysql = 0;
1158 }
static int qMySqlConnectionCount
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ isIdentifierEscapedImplementation

bool QMYSQLDriver::isIdentifierEscapedImplementation ( const QString identifier,
IdentifierType  type 
) const
protectedslot

Definition at line 1542 of file qsql_mysql.cpp.

1543 {
1544  Q_UNUSED(type);
1545  return identifier.size() > 2
1546  && identifier.startsWith(QLatin1Char('`')) //left delimited
1547  && identifier.endsWith(QLatin1Char('`')); //right delimited
1548 }
int type
Definition: qmetatype.cpp:239
bool startsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string starts with s; otherwise returns false.
Definition: qstring.cpp:3734
int size() const
Returns the number of characters in this string.
Definition: qstring.h:102
bool endsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string ends with s; otherwise returns false.
Definition: qstring.cpp:3796
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ open()

bool QMYSQLDriver::open ( const QString db,
const QString user,
const QString password,
const QString host,
int  port,
const QString options 
)
virtual

Derived classes must reimplement this pure virtual function to open a database connection on database db, using user name user, password password, host host, port port and connection options options.

The function must return true on success and false on failure.

See also
setOpen()

Implements QSqlDriver.

Definition at line 1229 of file qsql_mysql.cpp.

1235 {
1236  if (isOpen())
1237  close();
1238 
1239  /* This is a hack to get MySQL's stored procedure support working.
1240  Since a stored procedure _may_ return multiple result sets,
1241  we have to enable CLIEN_MULTI_STATEMENTS here, otherwise _any_
1242  stored procedure call will fail.
1243  */
1244  unsigned int optionFlags = Q_CLIENT_MULTI_STATEMENTS;
1245  const QStringList opts(connOpts.split(QLatin1Char(';'), QString::SkipEmptyParts));
1246  QString unixSocket;
1247 #if MYSQL_VERSION_ID >= 50000
1248  my_bool reconnect=false;
1249 #endif
1250 
1251  // extract the real options from the string
1252  for (int i = 0; i < opts.count(); ++i) {
1253  QString tmp(opts.at(i).simplified());
1254  int idx;
1255  if ((idx = tmp.indexOf(QLatin1Char('='))) != -1) {
1256  QString val = tmp.mid(idx + 1).simplified();
1257  QString opt = tmp.left(idx).simplified();
1258  if (opt == QLatin1String("UNIX_SOCKET"))
1259  unixSocket = val;
1260 #if MYSQL_VERSION_ID >= 50000
1261  else if (opt == QLatin1String("MYSQL_OPT_RECONNECT")) {
1262  if (val == QLatin1String("TRUE") || val == QLatin1String("1") || val.isEmpty())
1263  reconnect = true;
1264  }
1265 #endif
1266  else if (val == QLatin1String("TRUE") || val == QLatin1String("1"))
1267  setOptionFlag(optionFlags, tmp.left(idx).simplified());
1268  else
1269  qWarning("QMYSQLDriver::open: Illegal connect option value '%s'",
1270  tmp.toLocal8Bit().constData());
1271  } else {
1272  setOptionFlag(optionFlags, tmp);
1273  }
1274  }
1275 
1276  if ((d->mysql = mysql_init((MYSQL*) 0)) &&
1277  mysql_real_connect(d->mysql,
1278  host.isNull() ? static_cast<const char *>(0)
1279  : host.toLocal8Bit().constData(),
1280  user.isNull() ? static_cast<const char *>(0)
1281  : user.toLocal8Bit().constData(),
1282  password.isNull() ? static_cast<const char *>(0)
1283  : password.toLocal8Bit().constData(),
1284  db.isNull() ? static_cast<const char *>(0)
1285  : db.toLocal8Bit().constData(),
1286  (port > -1) ? port : 0,
1287  unixSocket.isNull() ? static_cast<const char *>(0)
1288  : unixSocket.toLocal8Bit().constData(),
1289  optionFlags))
1290  {
1291  if (!db.isEmpty() && mysql_select_db(d->mysql, db.toLocal8Bit().constData())) {
1292  setLastError(qMakeError(tr("Unable to open database '") + db +
1294  mysql_close(d->mysql);
1295  setOpenError(true);
1296  return false;
1297  }
1298 #if MYSQL_VERSION_ID >= 50000
1299  if(reconnect)
1300  mysql_options(d->mysql, MYSQL_OPT_RECONNECT, &reconnect);
1301 #endif
1302  } else {
1303  setLastError(qMakeError(tr("Unable to connect"),
1305  mysql_close(d->mysql);
1306  d->mysql = NULL;
1307  setOpenError(true);
1308  return false;
1309  }
1310 
1311 #if (MYSQL_VERSION_ID >= 40113 && MYSQL_VERSION_ID < 50000) || MYSQL_VERSION_ID >= 50007
1312  // force the communication to be utf8
1313  mysql_set_character_set(d->mysql, "utf8");
1314 #endif
1315 #ifndef QT_NO_TEXTCODEC
1316  d->tc = codec(d->mysql);
1317 #endif
1318 
1319 #if MYSQL_VERSION_ID >= 40108
1320  d->preparedQuerysEnabled = mysql_get_client_version() >= 40108
1321  && mysql_get_server_version(d->mysql) >= 40100;
1322 #else
1323  d->preparedQuerysEnabled = false;
1324 #endif
1325 
1326 #ifndef QT_NO_THREAD
1327  mysql_thread_init();
1328 #endif
1329 
1330 
1331  setOpen(true);
1332  setOpenError(false);
1333  return true;
1334 }
static void setOptionFlag(uint &optionFlags, const QString &opt)
virtual void setOpen(bool o)
This function sets the open state of the database to open.
Definition: qsqldriver.cpp:283
QTextCodec * tc
Definition: qsql_mysql.cpp:90
virtual void setOpenError(bool e)
This function sets the open error state of the database to error.
Definition: qsqldriver.cpp:297
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QMYSQLDriverPrivate *p)
Definition: qsql_mysql.cpp:231
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
The QString class provides a Unicode character string.
Definition: qstring.h:83
QString left(int n) const Q_REQUIRED_RESULT
Returns a substring that contains the n leftmost characters of the string.
Definition: qstring.cpp:3664
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
Q_CORE_EXPORT void qWarning(const char *,...)
static QTextCodec * codec(MYSQL *mysql)
Definition: qsql_mysql.cpp:220
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT
Returns the local 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4049
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
bool isNull() const
Returns true if this string is null; otherwise returns false.
Definition: qstring.h:505
QString mid(int position, int n=-1) const Q_REQUIRED_RESULT
Returns a string that contains n characters of this string, starting at the specified position index...
Definition: qstring.cpp:3706
QString simplified() const Q_REQUIRED_RESULT
Returns a string that has whitespace removed from the start and the end, and that has each sequence o...
Definition: qstring.cpp:4415
#define Q_CLIENT_MULTI_STATEMENTS
Definition: qsql_mysql.cpp:74
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
void close()
Derived classes must reimplement this pure virtual function in order to close the database connection...
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ primaryIndex()

QSqlIndex QMYSQLDriver::primaryIndex ( const QString tableName) const
virtual

Returns the primary index for table tableName.

Returns an empty QSqlIndex if the table doesn't have a primary index. The default implementation returns an empty index.

Reimplemented from QSqlDriver.

Definition at line 1400 of file qsql_mysql.cpp.

1401 {
1402  QSqlIndex idx;
1403  if (!isOpen())
1404  return idx;
1405 
1406  QSqlQuery i(createResult());
1407  QString stmt(QLatin1String("show index from %1;"));
1408  QSqlRecord fil = record(tablename);
1409  i.exec(stmt.arg(tablename));
1410  while (i.isActive() && i.next()) {
1411  if (i.value(2).toString() == QLatin1String("PRIMARY")) {
1412  idx.append(fil.field(i.value(4).toString()));
1413  idx.setCursorName(i.value(0).toString());
1414  idx.setName(i.value(2).toString());
1415  }
1416  }
1417 
1418  return idx;
1419 }
The QSqlIndex class provides functions to manipulate and describe database indexes.
Definition: qsqlindex.h:55
QSqlResult * createResult() const
Creates an empty SQL result on the database.
void append(const QSqlField &field)
Appends the field field to the list of indexed fields.
Definition: qsqlindex.cpp:129
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
The QString class provides a Unicode character string.
Definition: qstring.h:83
QSqlRecord record(const QString &tablename) const
Returns a QSqlRecord populated with the names of the fields in table tableName.
void setName(const QString &name)
Sets the name of the index to name.
Definition: qsqlindex.cpp:110
void setCursorName(const QString &cursorName)
Sets the name of the cursor that the index is associated with to cursorName.
Definition: qsqlindex.cpp:266
QSqlField field(int i) const
Returns the field at position index.
Definition: qsqlrecord.cpp:289

◆ record()

QSqlRecord QMYSQLDriver::record ( const QString tableName) const
virtual

Returns a QSqlRecord populated with the names of the fields in table tableName.

Use query.

If no such table exists, an empty record is returned. The default implementation returns an empty record.

record() instead.

Reimplemented from QSqlDriver.

Definition at line 1421 of file qsql_mysql.cpp.

Referenced by primaryIndex().

1422 {
1423  QString table=tablename;
1425  table = stripDelimiters(table, QSqlDriver::TableName);
1426 
1427  QSqlRecord info;
1428  if (!isOpen())
1429  return info;
1430  MYSQL_RES* r = mysql_list_fields(d->mysql, table.toLocal8Bit().constData(), 0);
1431  if (!r) {
1432  return info;
1433  }
1434  MYSQL_FIELD* field;
1435 
1436  while ((field = mysql_fetch_field(r)))
1437  info.append(qToField(field, d->tc));
1438  mysql_free_result(r);
1439  return info;
1440 }
static mach_timebase_info_data_t info
QTextCodec * tc
Definition: qsql_mysql.cpp:90
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
The QSqlRecord class encapsulates a database record.
Definition: qsqlrecord.h:58
The QString class provides a Unicode character string.
Definition: qstring.h:83
static QSqlField qToField(MYSQL_FIELD *field, QTextCodec *tc)
Definition: qsql_mysql.cpp:292
bool isIdentifierEscaped(const QString &identifier, IdentifierType type) const
Returns whether identifier is escaped according to the database rules.
Definition: qsqldriver.cpp:429
QByteArray toLocal8Bit() const Q_REQUIRED_RESULT
Returns the local 8-bit representation of the string as a QByteArray.
Definition: qstring.cpp:4049
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
void append(const QSqlField &field)
Append a copy of field field to the end of the record.
Definition: qsqlrecord.cpp:312
QString stripDelimiters(const QString &identifier, IdentifierType type) const
Returns the identifier with the leading and trailing delimiters removed, identifier can either be a t...
Definition: qsqldriver.cpp:455
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ rollbackTransaction()

bool QMYSQLDriver::rollbackTransaction ( )
protectedvirtual

This function is called to rollback a transaction.

If successful, return true, otherwise return false. The default implementation does nothing and returns false.

See also
beginTransaction(), commitTransaction()

Reimplemented from QSqlDriver.

Definition at line 1481 of file qsql_mysql.cpp.

1482 {
1483 #ifndef CLIENT_TRANSACTIONS
1484  return false;
1485 #endif
1486  if (!isOpen()) {
1487  qWarning("QMYSQLDriver::rollbackTransaction: Database not open");
1488  return false;
1489  }
1490  if (mysql_query(d->mysql, "ROLLBACK")) {
1491  setLastError(qMakeError(tr("Unable to rollback transaction"),
1493  return false;
1494  }
1495  return true;
1496 }
static QSqlError qMakeError(const QString &err, QSqlError::ErrorType type, const QMYSQLDriverPrivate *p)
Definition: qsql_mysql.cpp:231
static QString tr(const char *sourceText, const char *comment=0, int n=-1)
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
Q_CORE_EXPORT void qWarning(const char *,...)
virtual void setLastError(const QSqlError &e)
This function is used to set the value of the last error, error, that occurred on the database...
Definition: qsqldriver.cpp:350
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

◆ tables()

QStringList QMYSQLDriver::tables ( QSql::TableType  tableType) const
virtual

Returns a list of the names of the tables in the database.

The default implementation returns an empty list.

The tableType argument describes what types of tables should be returned. Due to binary compatibility, the string contains the value of the enum QSql::TableTypes as text. An empty string should be treated as QSql::Tables for backward compatibility.

Reimplemented from QSqlDriver.

Definition at line 1354 of file qsql_mysql.cpp.

1355 {
1356  QStringList tl;
1357 #if MYSQL_VERSION_ID >= 40100
1358  if( mysql_get_server_version(d->mysql) < 50000)
1359  {
1360 #endif
1361  if (!isOpen())
1362  return tl;
1363  if (!(type & QSql::Tables))
1364  return tl;
1365 
1366  MYSQL_RES* tableRes = mysql_list_tables(d->mysql, NULL);
1367  MYSQL_ROW row;
1368  int i = 0;
1369  while (tableRes) {
1370  mysql_data_seek(tableRes, i);
1371  row = mysql_fetch_row(tableRes);
1372  if (!row)
1373  break;
1374  tl.append(toUnicode(d->tc, row[0]));
1375  i++;
1376  }
1377  mysql_free_result(tableRes);
1378 #if MYSQL_VERSION_ID >= 40100
1379  } else {
1380  QSqlQuery q(createResult());
1381  if(type & QSql::Tables) {
1382  QString sql = QLatin1String("select table_name from information_schema.tables where table_schema = '") + QLatin1String(d->mysql->db) + QLatin1String("' and table_type = 'BASE TABLE'");
1383  q.exec(sql);
1384 
1385  while(q.next())
1386  tl.append(q.value(0).toString());
1387  }
1388  if(type & QSql::Views) {
1389  QString sql = QLatin1String("select table_name from information_schema.tables where table_schema = '") + QLatin1String(d->mysql->db) + QLatin1String("' and table_type = 'VIEW'");
1390  q.exec(sql);
1391 
1392  while(q.next())
1393  tl.append(q.value(0).toString());
1394  }
1395  }
1396 #endif
1397  return tl;
1398 }
QSqlResult * createResult() const
Creates an empty SQL result on the database.
int type
Definition: qmetatype.cpp:239
QTextCodec * tc
Definition: qsql_mysql.cpp:90
The QSqlQuery class provides a means of executing and manipulating SQL statements.
Definition: qsqlquery.h:63
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
virtual bool isOpen() const
Returns true if the database connection is open; otherwise returns false.
Definition: qsqldriver.cpp:182
The QString class provides a Unicode character string.
Definition: qstring.h:83
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
static QString toUnicode(QTextCodec *tc, const char *str)
Definition: qsql_mysql.cpp:95
QMYSQLDriverPrivate * d
Definition: qsql_mysql.h:136

Friends and Related Functions

◆ QMYSQLResult

friend class QMYSQLResult
friend

Definition at line 105 of file qsql_mysql.h.

Referenced by createResult().

Properties

◆ d

QMYSQLDriverPrivate* QMYSQLDriver::d
private

The documentation for this class was generated from the following files: