inserting data from perl into mysql - sql

I'm trying to insert data produced by perl into an oracle database table using perl DBI. Its the first time I've tried this so its likely I'm making a simple mistake.
What i'm using at the moment is:
$dbh = DBI->connect ('dbi:Oracle:geosgen','student','train')
|| die "Database connection not made: $DBI::errstr";
$sql = "INSERT INTO MYTEST VALUES ($series, $sheet, $maxlat, $minlat, $maxlong, $minlong)";
$create = $dbh->do($sql);
print "Content-type:text/html\n\n\n";
if($Create){
print "Success";
}
else{
print "Failure<br/>$DBI::errstr";
}
and the output I get is like this:
DBD::Oracle::db do failed: ORA-00917: missing comma (DBD ERROR: error possibly near <*> indicator at char 36 in 'INSERT INTO MYTEST VALUES (Scotland <*>one inch 1st, Shetland Islands (North) (131), -0.6800, -1.4100, 60.9700, 60.6900)') [for Statement "INSERT INTO MYTEST VALUES (Scotland one inch 1st, Shetland Islands (North) (131), -0.6800, -1.4100, 60.9700, 60.6900)"] at bruce1.pl line 69, <INPUT> line 924.
Content-type:text/html
meaning it has read the data in successfully but failed. I expect I've made a rookie error, is there anything obvious?

SQL requires alphabetic constants to be quoted:
INSERT INTO MYTEST VALUES ('Scotland one inch 1st', 'Shetland Islands (North) (131)', -0.6800, -1.4100, 60.9700, 60.6900)
If you print the value of $sql, you will see that they aren't.

Related

Perl concatenation for SQL query

I'm trying to transfer the content of a CSV file into a table in PostgreSQL using Perl.
I'm able to update my table successfully, but the terminal returns an error:
Use of uninitialized value in concatenation (.) or string
Syntax error near ","
INSERT INTO test VALUES (, '', '', '', '',, )
Here is the code where it fails :
for (my $i=0 ; $i<=50; $i++){
$dbh ->do("INSERT INTO test VALUES ('$LastName[$i]', '$Street[$i]', $Balance_account[$i])") ;
If more information is needed just ask them.
Sorry for the bad English.
--
Thomas
Use placeholders,
for (my $i=0 ; $i<=50; $i++){
$dbh->do("INSERT INTO test VALUES (?,?,?)",
undef,
$LastName[$i], $Street[$i], $Balance_account[$i]
);
}
Ideally, you should prepare the query and execute for each set of values, something like this:
my $sth = $dbh->prepare('INSERT INTO test VALUES (?,?,?)');
for (my $i=0 ; $i<=50; $i++){
$sth->execute($LastName[$i], $Street[$i], $Balance_account[$i]);
}
My guess is that your error is being caused by not specifying the column names in your insert, while simultaneously having the wrong number/types of columns. I would expect the following Perl code to not error out:
for (my $i=0 ; $i<=50; $i++){
$dbh -> do("INSERT INTO test (lastname, street, balance) VALUES ('$LastName[$i]', '$Street[$i]', $Balance_account[$i])");
Here is what a working query might look like:
INSERT INTO test (lastname, street, balance)
VALUES
('Skeet', '100 Thatcher Street', 100.50);
It is generally considered bad practice to not include column names while doing an insert, because even if you get it right, it could easily break later on.

Oracle DBD Error from Perl script

I am trying to run perl script but i get an oracle error.
DBD::Oracle::db prepare failed: ORA-01756: quoted string not properly terminated (DBD ERROR: OCIStmtPrepare)
But this SQL QUERY perfectly works fine in TOAD
MY perl connection details:
my $dbh = DBI->connect($dsn, $dbuser, $dbpass, { RaiseError => 1, AutoCommit => 0 });
my $sth=$dbh->prepare($SQL);
$sth->execute or die "EXEC ERROR $sth->errstr";
sql query:
SELECT name FROM employee WHERE
event IN ('IPO', 'RIGHTS')
AND (NOT market_code = 'ID' OR NOT event = 'RIGHTS')
AND NOT market_code = 'IN'
AND NOT market_code = 'NZ'
AND name NOT LIKE '%stat%'
AND NOT REGEXP_LIKE (name, 'S.K(Q|S)$')
AND name NOT LIKE '.%'
AND name NOT LIKE '%ol.SI'
AND name NOT LIKE '%bi.SI'
Perl will interpolate double-quoted string literals, like
my $SQL = "REGEXP_LIKE (name, 'S.K(Q|S)$')";
In here, your "variable" $' will be replaced with its value.
If you don't want that, use a non-interpolating version:
my $SQL = q{REGEXP_LIKE (name, 'S.K(Q|S)$')};
Single-quoted strings would also do, but since you have single quotes inside, the q{} is convenient. You can choose any terminator you want (such as q[]) and you can make it interpolate, too, with qq{}.

[ODBC Microsoft Access Driver]COUNT field incorrect

$q = 'INSERT INTO MyTable(proddesc, qnty, PriceH, PriceA, PriceL) VALUES(?,?,?,?,?)';
$sth = odbc_prepare($dbConn, $q);
$success = odbc_execute($sth, array(my 5 variables that are not null));
It gives me the above error - [ODBC Microsoft Access Driver] COUNT field incorrect. I know that the query is correct because I ran it in Access and it was fine. I think I may be using the prepare/execute statements incorrectly.
I also encountered this now and the solution I did to fix it is to quote the variables properly.
Try printing your $q and you will see if it needs to be quoted.
You can try these too:
INSERT INTO TABLE -- quote db and table names using (`) "grave accent" character
VALUES( 'Fed''s' ) -- quote the apostrophes

PDO statement error for "SUM"

I have a query that im trying to collect tallys from fields in one query to avoid querying 4 times i added them all into one query.
But i am getting this error:
SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
')) as english,
sum(if(class='2')) as science,
sum(if(class='3')) as french
F' at line 3
I'm not sure how the syntax is meant to be for this so was hopeing some one might know... my query is this:
$stmt = $pdo->prepare("SELECT
count(id) AS total,
sum(if(class=?)) as english,
sum(if(class=?)) as science,
sum(if(class=?)) as french
FROM school");
try{
$stmt->execute(array(1,2,3));
} catch (PDOException $e){
echo $e -> getMessage(); exit;
}
Does any one know the correct syntax for this ?
At least, you have missed a right bracket in each sum line.
Then, Im not sure about if(..,..,..) statement, I usually write CASE WHEN (condition) THEN expr1 ELSE expr2 END

SQLAlchemy ProgrammingError - how to debug?

I'm using SQLAlchemy 0.5.8, and seeing this error:
ProgrammingError: (ProgrammingError) can't adapt 'INSERT INTO enumeration_value (id,
key_id, code, name, notes) VALUES (%(id)s, %(key_id)s, %(code)s, %(name)s, %(notes)s)'
{'key_id': 'aac6fc29-4ccd-4fe4-9118-cfbbd04449fe', 'notes': '', 'code': (u'Barnet',),
'id': 'd0540c97-882e-4a5b-bf14-b3ebcfeea051', 'name': (u'Barnet',)}
But a direct SQL insert with the values from the error seems to work just fine:
=> INSERT INTO enumeration_value (id, key_id, code, name, notes)
VALUES ('d0540c97-882e-4a5b-bf14-b3ebcfeea051', 'aac6fc29-4ccd-4fe4-9118-cfbbd04449fe',
'Barnet', 'Barnet', '');
INSERT 0 1
If the direct SQL works OK, how can I start to debug this?
Incidentally, the line that's throwing the error doesn't seem to have an INSERT statement in it at all, so I am a bit confused:
File "----barnet.py", line 117, in load_file
instance = model.Session.query(model.EnumerationValue).filter_by(key=key_barnet_level_2, code=level_2).all()
Do SQLAlchemy filter statements generate INSERT commands, or does this just happen to be the last line before things start to go wrong?
Figured it out - the problem was actually a syntax error a few lines higher up, with a rogue comma:
key_from = code,
Sorry if I wasted anyone's time. Please close the question.