Can't get mysql_query to work, mysql_error displays nothing - mysqli

Recently converted from mysql to mysqli and things were working fine. Connect, select still work fine but now one query fails. Here is the basic code:
Connect to database ($con) - successful.
mysqli_query to select some data from table1 (fn1, ln1, yr1) - successful.
Table data goes to $fn, $ln, $yr after mysql_fetch_array - successful.
Use the data to form an insert:
$sql = "insert into table2 (fn2, ln2, yr2) values ('$fn', '$ln', '$yr')";
mysql-query($con, $sql) or die ("Insert failed: " . mysqli_error($con));
The query fail with the Insert failed message but no reason from mysql_error.
What have I missed?

I've try it. It work. Insert it's ok!
$link = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$qry = "insert into reputazione (iduser,star,votante,commento)
values(10,5,\"pippo\",\"commento\")";
mysqli_query($link, $qry);
if (mysqli_affected_rows($link) > 0) {
echo "ok!";
}

Okay, I solved the problem by coding all the mysqli commands in-line and not calling functions and passing the sql statements to them. I had functions for connecting to the DB, selecting from one table, inserting into another table and then deleting from the first table.

Related

The sql works fine but with python it doesn't insert values into table

I'm trying to use python for stored procs in sql, I have tested my sql code and it works fine, but when I execute it via python, the values are not inserted into my table
Note: I don't have any errors when executing
My code below:
import psycopg2
con = psycopg2.connect(dbname='dbname'
, host='host'
, port='5439', user='username', password='password')
def executeScriptsfromFile(filename):
#Open and read the file as a single buffer
cur = con.cursor()
fd = open(filename,'r')
sqlFile = fd.read()
fd.close()
#all SQL commands(split on ';')
sqlCommands = filter(None,sqlFile.split(';'))
#Execute every command from the input file
for command in sqlCommands:
# This will skip and report errors
# For example, if the tables do not yet exist, this will skip over
# the DROP TABLE commands
try:
cur.execute(command)
con.commit()
except Exception as inst:
print("Command skipped:", inst)
cur.close()
executeScriptsfromFile('filepath.sql')
Insert comment in sql:
INSERT INTO schema.users
SELECT
UserId
,Country
,InstallDate
,LastConnectDate
FROM #Source;
Note: As I said the sql works perfectly fine when I tested it.

SELECT CURRVAL (pg_get_serial_sequence Im doing something wrong?

What am I doing wrong, I am trying to get the last record_id from a table, after the first statement inserts it into my table. I seem to just print the code that is meant to display the last id?
SELECT CURRVAL (pg_get_serial_sequence('sheet_tbl','sheet_id'))";
Code here
else {
echo 'Record added';
$sql = "INSERT INTO sheet_tbl (site_id, eventdate, eventtime, username, additionalvolunteers) VALUES ('$_POST[site_id]','$_POST[eventdate]','$_POST[eventtime]', '$username','$_POST[additionalvolunteers]')";
echo $sql; //Just so I can see what is getting sent
$result = pg_query($sql);
$sheet_id_pull = "SELECT CURRVAL (pg_get_serial_sequence('sheet_tbl','sheet_id'))";
echo $sheet_id_pull; //This is where im having the issue with the above line.
}
Maybe
echo pg_query($sheet_id_pull);
Instead of
echo $sheet_id_pull;
Or
$sheet_id_pull = pg_query("SELECT CURRVAL (pg_get_serial_sequence('sheet_tbl','sheet_id'))");
echo $sheet_id_pull;
Also read this question. It has a better way of getting the inserted id.

sqlalchemy import export failing on IntegrityError

I'm writing an sqlalchemy import/export script using the serializer dumps and loads.
The export works, but I have problems with the import, mainly due to foreign key issues.
I'm using sorted_tables to get the list of tables sorted based on dependencies and this makes sure I won't have cross tables foreign key issues but is there something similar to handle internal foreign keys (a table pointing to itself)?
I'm basically thinking about 2 possible solutions:
Find a way to sort the rows based on the dependencies
Disable all constraints -> insert the data -> enable all constraints
again
but I'm not sure how to do this properly...
a table example:
class Employee(Base):
__tablename__ = "t_employee"
id = sa.Column(Identifier, sa.Sequence('%s_id_seq' % __tablename__), primary_key=True, nullable=False)
first_name = sa.Column(sa.String(30))
last_name = sa.Column(sa.String(30))
manager_id = sa.Column(Identifier, sa.ForeignKey("t_employee.id", ondelete='SET NULL'))
and here is my script:
def export_db(tar_file):
print "Exporting Database. This may take some time. Please wait ..."
Base.metadata.create_all(engine)
tables = Base.metadata.tables
with tarfile.open(tar_file, "w:bz2") as tar:
for tbl in tables:
print "Exporting table %s ..." % tbl
table_dump = dumps(engine.execute(tables[tbl].select()).fetchall())
ti = tarfile.TarInfo(tbl)
ti.size = len(table_dump)
tar.addfile(ti, StringIO(table_dump))
print "Database exported! Exiting!"
exit(0)
def import_db(tar_file):
print "Importing to Database. This may take some time. Please wait ..."
print "Dropping all tables ..."
Base.metadata.drop_all(engine)
print "Creating all tables ..."
Base.metadata.create_all(engine)
tables = Base.metadata.sorted_tables
with tarfile.open(tar_file, "r:bz2") as tar:
for tbl in tables:
try:
entry = tar.getmember(tbl.name)
print "Importing table %s ..." % entry.name
fileobj = tar.extractfile(entry)
table_dump = loads(fileobj.read(), Base.metadata, db)
for data in table_dump:
db.execute(tbl.insert(), strip_unicode(dict(**data)))
except:
traceback.print_exc(file=sys.stdout)
exit(0)
db.commit()
print "Database imported! Exiting!"
exit(0)
For mass dumps, the standard technique is to disable constraints, do the import, then re-enable them. You'll also get much faster performance on the inserts.

Best way to use Perl's DBI to UPDATE a row, and print the response to the cmd-line?

Have some Perl code which is using the DBI module - (the code is at work, I can post it in the morning if needed) - but mainly trying to get a sense of what DBI needs to do an update to a row -- and get either errors back, or confirmation that the UPDATE was executed.
(Below is just a basic example, feel free to give your own example and sample DDL if you want... just want some code that I know works. I've run my code via the Perl PtkDB debugger, and can "see" the SQL it generating and executing -- even paste in in the MySQL consol and execute it... but it's doing nothing in the Perl, even thought the select statements are working. Mainly just want a better idea of how DBI is handling UPDATE to MySQL, and if there's any built in feature in DBI that would make debugging this more simple. Thanks!)
So, please supply one full Perl script that:
Sets the connection (MySQL)
SELECT row two based on ID and get the first and last name
Lowercase the names
UPDATE the table
disconnect
Sample TABLE
<COL01>Id <COL02>FirstName <COL03>LastName
<ROW01-COL01>1 <ROW01-COL02>John <ROW01-COL03>Smith
<ROW02-COL01>2 <ROW02-COL02>Jane <ROW02-COL03>Doe
UPDATE (1): Code in question is below. The ONLY thing I've changed is remove code not related to the issue and the config info (eg database name, user, password, etc.) and made the value production for the variables super simple. This code was created by someone else and in a legacy code base.
use strict;
use warnings;
use DBI;
sub dbOpen {
my $dsn;
my $dbh;
$dsn = "DBI:mysql:database=databasename;host=localhost;port=3306";
$dbh = DBI->connect( $dsn, "root", "password" ) ||
print STDERR "FATAL: Could not connect to database.\n$DBI::errstr\n";
$dbh->{ AutoCommit } = 0;
return($dbh);
} # END sub dbOpen
my $Data;
$Data = &dbOpen();
my ($sql,$rs,$sql_update_result);
my $column2,
my $column3;
my $id;
$column2 = 2,
$column3 = 3;
$id = 1;
$sql = "UPDATE table SET column1 = NULL, column2 = ".$column2.", column3 = ".$column3." WHERE id = ".$id.";";
$rs = $Data->prepare( $sql );
$rs->execute() || &die_clean("Couldn't execute\n$sql\n".$Data->errstr."\n" );
($sql_update_result) = $rs->fetchrow;
$Data->disconnect();
DDL for MySQL -- if needed, just comment and I'll post one.
UPDATE (2):
Final found one complete example, though it's only for a select statement and not even inserting any VARs into the SQL: http://search.cpan.org/~timb/DBI/DBI.pm#Simple_Examples
Almost copy and paste from DBI Synopsis:
use DBI;
$dbh = DBI->connect($data_source, $username, $auth, \%attr);
$statement = "UPDATE some_table SET som_col = ? WHERE id = ?";
$rv = $dbh->do($statement, undef, $som_val, $id);
$DBI::err && die $DBI::errstr;
$rc = $dbh->disconnect;
I prefer to use do when updating or deleting since these operations doesn't return any row.
So, in order to have a little debug, i would modify your code like this:
my $sql = "UPDATE table SET column1=NULL, column2=$column2, column3=$column3 WHERE id=$id";
print STDERR "SQL: $sql\n"
my $numrows = $Data->do($sql);
if (not defined $numrows) {
print STDERR "ERROR: $DBI::errstr";
} else {
print STDERR "INFO: $numrows rows updated";
}
You can measure query response times from within your perl code, but since it is a database thing, i recommend you using any Mysql specialized tool (i don't use MySQL, sorry).
Have you considered something a bit higher level - like DBIx::Class?
You don't need to return the values, lowercase them in Perl, then update the rows. Just do that in one SQL statement:
my $sql = "UPDATE table SET column2=lower(column2) WHERE id = ?";
$sth = $dbh->prepare($sql);
foreach my $id (#ids) {
$sth->execute($id);
}
You also want to use placeholders to prevent Bobby Tables from visiting.

How do I insert data into a Postgres table using PowerShell or VBScript?

I need to periodically query the event logs on a handful of servers and insert specific events into a Postgres table.
I am having trouble figuring out how I can insert data into a table via ODBC using PowerShell and/or VBScript. I'm reasonably familiar with both VBScript and PowerShell generally, and I can craft a SQL UPDATE statement that works, I'm just trying to tie the two together, which I've never done before.
I have the Postgres ODBC driver installed, I've configured a data source which tests OK.
Google isn't helping me thus far, can someone provide some pointers?
What part are you having trouble with? How far have you got? Do you have a connection open? Do you know the syntax of the connection string?
Prepare a connection:
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open dsn, dbuser, dbpass
insert:
insert = "insert into table (col1, col2) values (12, 'Example Record')"
conn.Execute insert
If conn.errors.Count > 0 Then
Dim counter
WScript.echo "Error during insert"
For counter = 0 To conn.errors.Count
WScript.echo "Error #" & DataConn.errors(counter).Number
WScript.echo " Description(" & DataConn.errors(counter).Description & ")"
Next
Else
WScript.echo "insert: ok"
End If
for completeness, query:
query = "select * from table where col1 = 7"
Set recordSet = conn.execute(query)
' result is an object of type ADODB.RecordSet
If you want powershell, try this post.
If you need to know the connection string, try connectionstrings.com.
Thanks for the response.
I used more Googling and eventually grokked enough ADO.NET to get it working, although it may not necessarily be "correct".
$DBConnectionString = "Driver={PostgreSQL UNICODE};Server=$DBIP;Port=$DBPort;Database=$DBName;Uid=$DBUser;Pwd=$DBPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection
$DBConn.ConnectionString = $DBConnectionString
$DBCmd = $DBConn.CreateCommand()
[void]$DBCmd.Parameters.Add("#TimeStamp", [System.Data.Odbc.OdbcType]::varchar, 26)
[void]$DBCmd.Parameters.Add("#ErrorText", [System.Data.Odbc.OdbcType]::varchar, 4000)
$DBCmd.CommandText = "INSERT INTO errorinfo (errortime,xml) VALUES(?,?)"
$DBCmd.Connection.Open()
$DBCmd.Parameters["#TimeStamp"].Value = $TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")
$DBCmd.Parameters["#ErrorText"].Value = $ErrorText
[void]$DBCmd.ExecuteNonQuery()