mardi 28 juin 2016

MySQL Transaction returns error

So here's the stored procedure I've written. When I ran the DELETE and UPDATE in a single sql tab

as:

DELETE FROM curriculumsubjects WHERE curriculumId = 27;
INSERT INTO curriculumsubjects(curriculumId,subjectCode)
VALUES(27,'MATH101');

it works. It executes delete and insert without any problem

But if I call the stored procedure as:

CALL `enrollmentdb`.`updateCurriculumSubjects`(27, 'MATH101'); 

it returns the 'error' string i put during ROLLBACK

What could be causing the failure of transaction within the stored procedure body when it runs successfully if ran without stored procedure CALL?

Here's the stored procedure.

CREATE DEFINER=`root`@`localhost` PROCEDURE `updateCurriculumSubjects`(IN p_curriculumId int, IN p_subjectCode varchar(100))
BEGIN
    DECLARE hasError BOOLEAN DEFAULT 0;
    DECLARE CONTINUE HANDLER FOR sqlexception SET hasError = 1;

    START TRANSACTION;
        DELETE FROM curriculumsubjects WHERE curriculumId = p_curriculumId;
        INSERT INTO curriculumsubjects(curriculumId,subjectCode)
                                VALUES(p_curriculumId,p_subjCode);
    IF hasError THEN
        ROLLBACK;
        SELECT 'error';
    ELSE
        COMMIT;

    END IF;
END

By the way I'm using Mysql Workbench 6.3 and what I'm trying to do is to delete all the columns matching the curriculumId before I insert again.

On Java, I'll be iterating the call to the stored procedure for multiple inserts.

I hope you can help. I just can't find a reason why delete and insert won't work if put within a transaction.

Thanks.

Ratio or Percentage from group by SQL query from column with condition and without condition

I am having some trouble with a SQL query. From a table let's call it Reports:

I want to group all the reports by the name column.

Then for each of those name groups I want to go to the rating column and count the number of times the rating was 15 or less. Let's say this happened 10 times for one of the groups with the name BOBBO.

I also want to know the number of times ratings were submitted (same as total number of records for each name group). So using the name group BOBBO let's say he has 20 ratings.

So under the condition the group BOBBO 50% of the time has a rating 15 or less.

I've seen these posts -- I am still having some trouble cracking this.

using-count-and-return-percentage-against-sum-of-records

getting-two-counts-and-then-dividing-them

getting-a-percentage-from-mysql-with-a-group-by-condition-and-precision

divide-two-counts-from-one-select

After reading those I tried queries like these:

    ActiveRecord::Base.connection.execute
("SELECT COUNT(*) Matched,
     (select COUNT(rating) from reports group by name) Total,
     CAST(COUNT(*) AS FLOAT)/CAST((SELECT COUNT(*) FROM reports group by name) AS FLOAT)*100 Percentage from reports
    where rating <= 15 order by Percentage")


    ActiveRecord::Base.connection.execute
("select name, sum(rating) / count(rating) as bad_rating
 from reports group by name having bad_rating <= 15")

Any help would be very much appreciated!

Using Case When to Classify Customers in Teradata

I am researching customers and their shopping habits using SQL in Teradata.

Say I have the following information:

Table wklytrans
CustNm  GroceryStore  # WklyTrxns  Sum WklyTrxns  CustType
Jack    Publix        2            $70            Publix
Ruby    Kroger        1            $15            Both
Moe     Kroger        4            $120           Kroger
Ruby    Publix        1            $20            Both

I would like to create a new table that classifies them as follows:

CustNm  CustType  # PubTrxns  Sum PubTrxns  # KroTrxns  Sum KroTrxns
Jack    Publix    2           $70           NULL        NULL
Ruby    Both      1           $20           1           $15
Moe     Kroger    NULL        NULL          4           $120

The code I'm currently trying to run is as follows:

CREATE MULTISET VOLATILE TABLE custclass AS(
SEL
CustNm,
CustType,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Publix' THEN # WklyTrxns
WHEN CustType IN 'Publix' THEN # WklyTrxns
END AS # PubTrxns,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Publix' THEN Sum WklyTrxns
WHEN CustType IN 'Publix' THEN Sum WklyTrxns
END AS Sum PubTrxns,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Kroger' THEN # WklyTrxns
WHEN CustType IN 'Kroger' THEN # WklyTrxns
END AS # KroTrxns,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Kroger' THEN Sum WklyTrxns
WHEN CustType IN 'Kroger' THEN Sum WklyTrxns
END AS Sum KroTrxns
FROM wklytrans
)
WITH DATA                                      
PRIMARY INDEX (CustNm)                          
ON COMMIT PRESERVE ROWS;

This is what is currently being outputted:

CustNm  CustType  # PubTrxns  Sum PubTrxns  # KroTrxns  Sum KroTrxns
Jack    Publix    2           $70           NULL        NULL
Ruby    Both      1           $20           NULL        NULL
Ruby    Both      NULL        NULL          1           $15
Moe     Kroger    NULL        NULL          4           $120

How can I get my code to combine Ruby's transactions onto the same line so that it looks like the output I desire?

Any help is appreciated!

GAE Python - OperationalError: (2013, 'Lost connection to MySQL server during query')

I've been trying to connect to ClouSQL using Flexible Environments (vm:true)

but when I upload my app using:

gcloud preview app deploy --version MYVERSION

An error is thrown:

OperationalError: (2013, 'Lost connection to MySQL server during query')

I found out that it might be because the query is too large but I think that's not the case because it works locally and on production when I wans't using flexible environments with MySQLdb.

My code:

import os
import logging
import pymysql

class MySQL(object):
    '''
    classdocs
    '''
    # TO INSTALL LOCAL DB: http://stackoverflow.com/questions/30893734/no-module-named-mysql-google-app-engine-django


    @classmethod
    def getConnection(cls):
        # When running on Google App Engine, use the special unix socket
        # to connect to Cloud SQL.
        if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
            logging.debug('PROJECT [%s], INSTANCE[%s] - USER [%s] - PASS [%s], SCHEMA [%s]',
                          os.getenv('CLOUDSQL_PROJECT'),
                          os.getenv('CLOUDSQL_INSTANCE'),
                          os.getenv('CLOUDSQL_USER'),
                          os.getenv('CLOUDSQL_PASS'),
                          os.getenv('CLOUDSQL_SCHEMA'))

            db = pymysql.connect(unix_socket='/cloudsql/APP:REGION:INSTANCENAME')
                    #os.getenv('CLOUDSQL_PROJECT'),
                    #os.getenv('CLOUDSQL_INSTANCE')), 
                    #user=os.getenv('CLOUDSQL_USER'),
                    #passwd=os.getenv('CLOUDSQL_PASS'),  
                    #db=os.getenv('CLOUDSQL_SCHEMA'))
        # When running locally, you can either connect to a local running
        # MySQL instance, or connect to your Cloud SQL instance over TCP.
        else:
            db = pymysql.connect(host=os.getenv('DBDEV_HOST'), user=os.getenv('DBDEV_USER'), 
                                 passwd=os.getenv('DBDEV_PASS', ''), db=os.getenv('DBDEV_SCHEMA'))

        return db

Any thoughts on this?

Thanks!

"set names" vs mysqli_set_charset — besides affecting mysqli_escape_string, are they identical?

It seems to be common knowledge to use mysql_set_charset / mysqli::set_charset instead of the direct MySQL query set names.

The reason often cited is that set names is insecure because the encoding used for mysql_real_escape_string / mysqli::real_escape_string will only be set by a call to mysql_set_charset / mysqli::set_charset. (Another reason cited is that the PHP docs says it's "not recommended" §.)

However, is it safe to use the direct MySQL query set names if we use prepared statements andor other means of escaping besides mysql_real_escape_string / mysqli::real_escape_string / mysqli_escape_string?

Besides affecting the encoding of mysql_real_escape_string / mysqli::real_escape_string / mysqli_escape_string, Is there any difference between set names vs mysql_set_charset/mysqli::set_charset?

Undefined text in lines 6,9 and 10. Why am I getting this error? [duplicate]

This question already has an answer here:

t1 has username,

t2 has password.

The page from which this is redirected has another field t3, which compares t2 and t3.

This error started appearing only after adding this t2 and t3 comparison

removal of the t3 check makes this work again.

<?php
$con = mysqli_connect("localhost","root","","company");
if(mysqli_connect_errno()){
    echo "Could not connect.";
}
$query = "SELECT * FROM login_info WHERE suser = '{$_POST['t1']}'"; //line 6
$queryArray = mysqli_fetch_array(mysqli_query($con,$query));
if(empty($queryArray['suser'])){
    echo "<h2 style='font-size: 40px;'><br><br><br><br><center><font face=Papyrus color=#425A87 style='text-shadow: 0px 0px 7px white;'>Welcome, user ".$_POST['t1'].". This is your first login to this website.</font></center></h2>"; //line 9
    mysqli_query($con,"INSERT INTO login_info VALUES ('{$_POST['t1']}','{$_POST['t2']}')");  //line 10
} 
else{
    echo "<h2 style='font-size: 40px;'><br><br><br><br><center><font face=Papyrus color=#425A87 style='text-shadow: 0px 0px 7px white;'>Welcome back ".$_POST['t1']."</font></center></h2>";
}
mysqli_close($con);     
require_once 'display.php';
?>

how to get similar search results in MySQL?

I am trying to search by words similarity or even if someone made a typo.

For example if anyone searches with picadilly correct one is piccadilly, It should get the result.

I had tried by searching by removing a char from last until 3 chars left using PHP, for example picadilly picadill picadil picadi picad pica pic

It's working but I am also getting unwanted results (due to shorten of keyword to 3 chars) which aren't similar, Also don't think it is a good way, Is there any better approach ?

Table Structure & Data:

+----+---------------------------+------------------------------------------------------+
| id | name                      | address                                              |
+----+---------------------------+------------------------------------------------------+
|  1 | Bethnal Green Station     | Bethnal Green Tube Station, London, E2 0ET           |
|  2 | Westminster Station       | Westminster Tube Station, London, SW1A 2JR           |
|  3 | Goldhawk Road Station     | Goldhawk Road Tube Station, London, W12 8EG          |
|  4 | Piccadilly Circus Station | Piccadilly Circus Tube Station, London, W1J 9HP      |
|  5 | Ravenscourt Park Station  | Ravenscourt Park Tube Station, London, W6 0JJ        |
|  6 | Barons Court Station      | Barons Court Tube Station, London, W14 9EA           |
|  7 | Charing Cross Station     | Charing Cross Tube & Train Station, London, WC2N 6RQ |
|  8 | Hammersmith Station       | Hammersmith Tube Station, London, W6 8AB             |
|  9 | Embankment Station        | Embankment Tube Station, London, WC2N 6NS            |
| 10 | Leicester Square Station  | Leicester Square Tube Station, London, WC2H 0AP      |
+----+---------------------------+------------------------------------------------------+

Query:

SELECT * FROM `stations`
WHERE name like '%picadilly%'
   OR name like '%picadill%'
   OR name like '%picadil%'
   OR name like '%picadi%'
   OR name like '%picad%'
   OR name like '%pica%'
   OR name like '%pic%'