Perl replaces single quotes to double quotes string - regex

My Script want to replace or remove the single quotes with double quotes
str_replace(rtrim(c_manager),~s/\'/\'\'/g) this line cannot work it out..
Example: k'amal
Result : k"amal or kamal
$sql = 'select rtrim(f_admin_disabled),'."\n".
' convert(varchar,t_password,101),'."\n".
' rtrim(c_email),'."\n".
' str_replace(rtrim(c_manager),~s/\'/\'\'/g),'."\n".
' rtrim(c_mgr_email)'."\n".
' from tuserprofile'."\n".
' where ic_user1 = '."'$user_id'"."\n";
$sth = $dbh->prepare("$sql")
or err("Database error in $sql", "Error preparing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->execute or err("Database error in $sql", "Error executing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->bind_columns(\$prev_status, \$prev_date, \$prev_email, \$prev_mngr_name, \$prev_mngr_email);
$sth->fetch();
$sth->finish();
if($user_email ne $prev_email){
$sql = 'declare #result int'."\n".
'exec #result = ap_recert_update '."'$user_id', '$prev_date', ".
"'$prev_status', '$user_email', ".
"'$prev_mngr_name', '$prev_mngr_email' "."\n".
'SELECT #result'."\n";
$sth = $dbh->prepare("$sql")
or err("Database error in $sql", "Error preparing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->execute or err("Database error in $sql", "Error executing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->bind_columns( \$result);
$sth->fetch();
if($result < 0){
err("", $user_id."\t".$result, 0);
$problem = $problem.$user_id."\t".$result."\n";
}
$sth->finish();
}
}
}

Don't include your variables directly in your sql statements. Instead use placeholders and bind variables.
Cleaning up your first sql statement would be done like follows:
my $sql = q{select rtrim(f_admin_disabled),
convert(varchar,t_password,101),
rtrim(c_email),
str_replace(rtrim(c_manager),~s/'/''/g),
rtrim(c_mgr_email)
from tuserprofile
where ic_user1 =?};
$sth = $dbh->prepare($sql)
or err("Database error in $sql", "Error preparing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->execute($user_id) or err("Database error in $sql", "Error executing SQL statement:\r\n\n" . $dbh->errstr, 3);
$sth->bind_columns(\($prev_status, $prev_date, $prev_email, $prev_mngr_name, $prev_mngr_email));
$sth->fetch();
$sth->finish();
Also could just use a heredoc for the assignment to $sql
my $sql = <<'END_SQL';
select rtrim(f_admin_disabled),
convert(varchar,t_password,101),
rtrim(c_email),
str_replace(rtrim(c_manager),~s/'/''/g),
rtrim(c_mgr_email)
from tuserprofile
where ic_user1 =?
END_SQL

Related

how to show a variable in MESSAGE_TEXT in signal query in c++

I am using Signal query to catch errors in my c++ programming:
in the program user has to enter a database name and i check the database if it does not exists I have to return proper error message:
std::string database_name;
std::cin<<database_name;
if(!exists(database_name)){
query="SIGNAL SQLSTATE '42000' SET MYSQL_ERRNO='1049', MESSAGE_TEXT = 'Unknown database';";
}
how can I print the database_name variable after Unknown database?
You can format the string using
query = std::format( "... MESSAGE_TEXT = 'Unknown database {}'", database_name );
This will replace {} with the first string argument (database_name)
Or you could use a string stream like
std::ostringstream ss;
ss << "... MESSAGE_TEXT = 'Unknown database '" << database_name << "'";
query = ss.str();

Cannot insert special symbols to Oracle database

I tried to add special symbols (i.e : æ_ø_å_Æ_Ø_Å_____£€$&#%¿) to Oracle database table VARCHAR2 column and different results noticed in following methods.
Database character set : SELECT * FROM nls_database_parameters WHERE parameter LIKE '%SET';
NLS_NCHAR_CHARACTERSET AL16UTF16
NLS_CHARACTERSET WE8MSWIN1252
SQL used :
INSERT INTO Test(C1) VALUES('æ_ø_å_Æ_Ø_Å_____£€$&#%¿');
Insert Directly via SQL Developer
Result : æ_ø_å_Æ_Ø_Å_____£€$&#%¿
Insert via SQLPlus
Result : ¿¿_¿¿_¿¿_¿¿_¿¿_¿¿_____¿¿¿¿¿$&#%¿¿
Insert via C++ code using SOCI library
Result :
While using database connection string (WINDOWS_1252 charset) : "oracle://service=<service> user=<user> password=<password> charset=178 ncharset=1000"; result was
æ_ø_å_Æ_Ø_Å_____£€$&#%¿
While using database connection string (UTF_8 charset) : "oracle://service=<service> user=<user> password=<password> charset=871ncharset=1000"; result was
æ_ø_å_Æ_Ø_Å_____£€$&#%¿
C++ code used :
std::string dbConnectionString = "oracle://service=<service> user=<user> password=<password> charset=178 ncharset=1000";
soci::session dbCon;
dbCon.open(dbConnectionString.c_str());
soci::statement *cursor = nullptr;
std::string selectString ="INSERT INTO Test(C1) VALUES('æ_ø_å_Æ_Ø_Å_____£€$&#%¿')";
try
{
cursor = new soci::statement(dbCon);
cursor ->alloc();
cursor ->prepare(selectString);
cursor ->define_and_bind();
cursor ->execute(true);
}
catch (soci::soci_error const & e)
{
std::cout <<"ERROR : ." << e.get_error_category() << " : "<<e.what()<< std::endl;
}
What is the reason for this inconsistent behavior?

Getting number of columns in a table using ' Proc C-C``

I am using the below code to get the number of columns in an oracle table.
char selectQuery[30000] = {'\0'};
strcpy(selectQuery, "SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME=\'");
strcat(selectQuery, tableName);
strcat(selectQuery, "\'");
strcpy((char*) stmt.arr, selectQuery);
stmt.len = strlen((char*) stmt.arr );
stmt.arr[stmt.len]= '\0';
EXEC SQL WHENEVER SQLERROR CONTINUE;
EXEC SQL WHENEVER NOT FOUND CONTINUE;
EXEC SQL DECLARE SELECTCOLNU STATEMENT;
EXEC SQL PREPARE SELECTCOLNU FROM :stmt;
if(sqlca.sqlcode != 0)
{
DEBUG_LOG("SQL-ERR:Preparation of SELECT Query to get number of columns failed: Ora-Err: %d %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
return PREPARATION_FAILURE;
}
EXEC SQL EXECUTE SELECTCOLNU INTO:columnsNo;
if(sqlca.sqlcode < 0)
{
DEBUG_LOG("SQL-ERR:Execute failed: Ora-Err: %d %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
return EXECTUION_FAILURE;
}
DEBUG_LOG("Number of columns: %d\n", columnsNo);
When I execute the code, It doesn't give any error but I am getting "Number of columns: 0" as the output.
There are few columns in the table I am referring.
Am I doing anything wrong here?
Below is the declaration section...
EXEC SQL BEGIN DECLARE SECTION;
int columnsNo;
VARCHAR stmt[MAX_SQL];
EXEC SQL END DECLARE SECTION;
Don't "escape" the ' in a C- string. It will have \' just in the string, and that is not what you want because the ' is the database string quote, which you now escape for the database and the database doesn't understand the query now.
sprintf(selectQuery, "SELECT COUNT(*) FROM USER_TAB_COLUMNS WHERE TABLE_NAME='%s'", tableName);
Note:
stmt.len = strlen((char*) stmt.arr );
stmt.arr[stmt.len]= '\0';
In the above strlen counts the number of characters until a null character. Thus stmt.arr[stmt.len] is already null. (No harm, though.)

Doctrine Querybuilder, binding Parameters

My Select function of my QueryManager:
/**
* Führt eine SELECT - Query durch
*
* #param $select = array( array(column, [...]), table, shortcut )
* $orderby = array(column, sorting-type)
* $where = array( array( column, value, type[or, and] ), [...] )
* $innerjoin = array( table, shortcut, condition )
* $pagination = array( page, limit )
*
* #return array $data
*/
public function select($select,$orderby, $where, $innerjoin, $pagination)
{
$qb = $this->conn->createQueryBuilder()
->select($select[0])
->from($select[1], $select[2])
;
if ($orderby) {
$qb->orderBy($orderby);
}
if ($where) {
foreach($where as $cond) {
$x = 0;
if ( key($cond) == 0 ) {
$qb
->where($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->andWhere($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->orWhere($cond[0] . ' = :' . $x)
->setParameter($x,$cond[1]);
}
$x++;
}
}
if ($innerjoin) {
$qb->join($select[2],$innerjoin);
}
$this->sql = $qb->getSQL();
$this->totalRowCount = count( $qb->execute() ) ;
if ($pagination) {
$max = $pagination[0] * $pagination[1];
$first = $max - $limit;
$qb
->setFirstResult($first)
->setMaxResults($max)
;
}
$stmt = $qb->execute();
return $stmt->fetchAll();
}
I don't know why, but in action, this function produces a select query without inserted values for the parameters:
/**
* Lädt einen User nach dessen Username
*
* #param $username
* #return User $user | null
*/
public function getUser($username)
{
if($data = $this->select(array('*','users','u'), null, array( array('username',$username) ), null,null)) {
return $user = $this->hydrate($data);
}
return null;
}
I didn't get a result, and the query is not setup correctly:
array(0) { }
SELECT * FROM users u WHERE username = ?
In my opinion the Builder doesn't supstitute my parameters with the provided values ...
I got the latest version of Doctrine DBAL (2.4) and this version should support this features!
Thanks for Help and Suggestions :)
I also had this Problem. I have readed here doctrine 2 querybuilder with set parameters not working that:
You cant bind parameters to QueryBuilder, only to Query
But im creating SQL conditions as collected AND & OR experssions in deep nested objects, and the toppest object creates the query object. So i cant create the query object before, i always return expression objects.
So i solved the problem with direct including the variable into the prepared variable's position.
$qb->where($cond[0] . '=' . $cond[1]);
And because i expect strings there i added hard coded quotes. This is not the desired way, but at the moment i dont know how to solve that in an other way with binding parameters to the QueryBuilder object.
$expr = $d_qb->expr()->between($t_c, "'" . $date_from . "'", "'" . $date_from . "'");
Other suggestions?
Following codes results:
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter('from', 1);
$d_qb->setParameter('to', 1);
or
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter(':from', 1);
$d_qb->setParameter(':to', 1);
Results:
e0_.created BETWEEN ? AND ?

Passing A Variable To SQL

I have a variable that is an IP address. It is saved as text in my Access 2010 database. I am trying to run this query with ipSrc and the query always fails. My guess is that its seeing ipSrc as ipSrc and not as the actual IP address. I tried it with 'ipSrc' and just plain ipSrc and both reurn fail. Also tried ""ipSrc"", failed as well. This failed to. '&ipSrc'. Here is the statement.
SQLCHAR* query = (SQLCHAR*)"SELECT tblIP.[IPAddress], tblIP.[IPType], tblIP.[IPStatus], tblIP.[IPMax] FROM tblIP WHERE tblIP.[IPAddress]= ipSrc AND tblIP.[IPType]=3 AND tblIP.[IPStatus]=1 AND tblIP.[IPMax]=0;";
and here is the definition of ipSrc.
translate_ip(ip_header->source_ip, ipSrc);
Using printf it prints out as an actual IP address.
printf("\n Source IP: %s", ipSrc);
There's no way for the code to know, from what you have there, that ipSrc should be treated specially, it's just going to pass it through as-is.
You can probably try to construct the query string dynamically as a C++ string, and then use that to populate the query. Something like:
std::string strqry =
"SELECT tblIP.[IPAddress], "
+ " tblIP.[IPType], "
+ " tblIP.[IPStatus], "
+ " tblIP.[IPMax] "
+ "FROM tblIP "
+ "WHERE tblIP.[IPAddress] = '" + ipSrc + "' "
+ "AND tblIP.[IPType] = 3 "
+ "AND tblIP.[IPStatus] = 1 "
+ "AND tblIP.[IPMax] = 0"
+ ";";
SQLCHAR *query = (SQLCHAR *)(strqry.c_str());
// Now use query
And make sure you have control over the ipSrc value. Otherwise, you're subject to SQL injection attacks (in which case you'll want to use prepared/parameterised statements).