Russian Qt Forum
Сентябрь 30, 2024, 12:34 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: 1 2 [3]   Вниз
  Печать  
Автор Тема: Наследование. Segmentation fault  (Прочитано 22735 раз)
MechanicalBear
Гость
« Ответ #30 : Декабрь 10, 2008, 13:58 »

Код:
../smartQuery/src/smartQuery.cpp: In copy constructor ‘smartQuery::smartQuery(const smartQuery&)’:
../smartQuery/src/smartQuery.cpp:21: предупреждение: base class ‘class QSqlQuery’ should be explicitly initialized in the copy constructor
что это значит?
похоже (я начинаю догадываться): базовый класс должен быть явно инициализирован в конструкторе копирования
буду пробовать
Записан
MechanicalBear
Гость
« Ответ #31 : Декабрь 11, 2008, 13:59 »

всё же я нашел ответ на этот сегфолт =)
всё оказалось очень просто: Наследование QSqlQuery._Segfault
« Последнее редактирование: Декабрь 11, 2008, 14:02 от MechanicalBear » Записан
shade-khv
Гость
« Ответ #32 : Декабрь 12, 2008, 03:06 »

Это у вас класс который реализует нормальную работу с запросами?
Записан
MechanicalBear
Гость
« Ответ #33 : Декабрь 12, 2008, 07:14 »

да. более удобное использование запросов. отдельные методы update insert select. а также дополнительные проверки и отладочные сообщения
Записан
shade-khv
Гость
« Ответ #34 : Декабрь 12, 2008, 08:27 »

Насколько я понимаю готовый запрос распарсить на  order, keys, values класс не способен?

Вообще интересно, должен же быть какой то общий, эталонный, чтоли, алгоритм разбора запроса (по крайней мере соответсвующего стандарту) на части? Сами то СУБД его как то разбирают.
Хотя, по моему Posgtes использует yacc для разбора (не уверен).

У меня есть мой класс в PHP, который работает с запросами, но метод разбиения там написан топорно:
Код
PHP
function setSQL($string)    //принимает строку запроса и разбивает его на смысловые части (select-список полей, where-условие отбора строк, order by-порядок сортировки)
{
$string=trim($string, ';'); $s=strtolower($string);
$uparts=array();
$tokens=array(' where ', ' order by ', ' group by ', ' from '); //задаем слова, служащие точками разбиения запроса
$b=0;
for ($i=0; $i<strlen($s); $i++)
foreach ($tokens as $token) if (substr($s, $i, strlen($token))==$token) {$uparts[]=substr($string, $b, $i-$b); $b=$i+1;}
if (strlen($s)-$b) $uparts[]=substr($string, $b, strlen($s)-$b);
foreach ($uparts as $upart) //перебираем части разбитого запроса и определем их в соответствующие элементы ассоциативного массива.
{
if (strtolower(substr($upart,0,4))=='from') $this->SQL['from']=$upart;
if (strtolower(substr($upart,0,6))=='select') $this->SQL['select']=$upart;
if (strtolower(substr($upart,0,5))=='where') $this->SQL['where']=$upart;
if (strtolower(substr($upart,0,8))=='order by') $this->SQL['order']=$upart;
if (strtolower(substr($upart,0,8))=='group by') $this->SQL['group']=$upart;
}
}

А вообще грамотный класс работы с запросами мне очень-очень интересен.
Записан
MechanicalBear
Гость
« Ответ #35 : Декабрь 12, 2008, 09:19 »

меня интересует один вопрос: зачем это нужно?
если ответишь - могу помочь, но несколько настораживает реализация. если нужно именно на PHP - думаю здесь не место.
Записан
shade-khv
Гость
« Ответ #36 : Декабрь 12, 2008, 09:52 »

Нет, на PHP у меня уже всё схвачено, я просто для примера привел.

Смысл такой что создавать объект проще. Можно создать его передав ему строку запроса (только что созданного и проверенного в PgAdmin-е, например). При создании в конструкторе строка разберется на where, sort, group и прочие части, каждую из которых можно легко менять. Например, чтобы позволить пользователю в процессе работы выбирать какие столбцы запрашивать из БД.
Записан
shade-khv
Гость
« Ответ #37 : Декабрь 12, 2008, 09:59 »

Просто я не совсем понял как будет строиться запрос если мы создали объект конструктором
 smartQuery      ( const QString &query = QString(), QSqlDatabase db = QSqlDatabase());
Записан
MechanicalBear
Гость
« Ответ #38 : Декабрь 12, 2008, 10:40 »

допустим, часто используется конструкция добавить/изменить
Код
C++ (Qt)
smartQuery sq;
sq.addValue("value1", value1);
sq.addValue("value2", value2);
if (edit)
   sq.update(_table, "k", k);
else
   sq.insert(_table);
 
то есть smartQuery можно использовать как стандартную QSqlQuery с возможностью указать запрос в конструкторе, а также задействовать дополнительные методы, верные только для нее
Записан
ритт
Гость
« Ответ #39 : Декабрь 12, 2008, 10:53 »

Цитировать
QString QSqlDriver::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.

Цитировать
QString QSqlDriver::formatValue ( const QSqlField & field, bool trimStrings = false ) const   [virtual]
Returns a string representation of the field value for the database. 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.

Цитировать
QString QSqlDriver::sqlStatement ( StatementType type, const QString & tableName, const QSqlRecord & rec, bool preparedStatement ) const   [virtual]
Returns a SQL statement of type type for the table tableName with the values from rec. If preparedStatement is true, the string will contain placeholders instead of values.
This method can be used to manipulate tables without having to worry about database-dependent SQL dialects. For non-prepared statements, the values will be properly escaped.
Записан
MechanicalBear
Гость
« Ответ #40 : Декабрь 12, 2008, 13:30 »

Цитировать
QString QSqlDriver::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.

Цитировать
QString QSqlDriver::formatValue ( const QSqlField & field, bool trimStrings = false ) const   [virtual]
Returns a string representation of the field value for the database. 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.

Цитировать
QString QSqlDriver::sqlStatement ( StatementType type, const QString & tableName, const QSqlRecord & rec, bool preparedStatement ) const   [virtual]
Returns a SQL statement of type type for the table tableName with the values from rec. If preparedStatement is true, the string will contain placeholders instead of values.
This method can be used to manipulate tables without having to worry about database-dependent SQL dialects. For non-prepared statements, the values will be properly escaped.
кхм.. это к чему?
Записан
BRE
Гость
« Ответ #41 : Декабрь 12, 2008, 13:39 »

кхм.. это к чему?
Это к тому, что есть штатные средства, которые формируют строки запросов, причем опираясь на специфику конкретной базы данных (в зависимости от драйвера).
 Подмигивающий
Записан
MechanicalBear
Гость
« Ответ #42 : Декабрь 15, 2008, 07:38 »

это не по моей теме
Записан
Страниц: 1 2 [3]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.28 секунд. Запросов: 21.