I simply want to execute the following Mysql statement
SET #a = 1;SELECT #a;
with MySql.Data.MySqlClient
[System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$password = 'mypassword'
$sql = "SET #a = 1;SELECT #a;"
$server = 'localhost'
$port = 3306
$database = 'test'
$User = 'root'
$conn=new-object MySql.Data.MySqlClient.MySqlConnection
$connectionstring = "Server=$Server;Port=$port;Database=$DataBase;Uid=$User;Pwd=$Password;allow zero datetime=yes"
$conn.ConnectionString = $connectionstring
$conn.Open()
$cmd=new-object MySql.Data.MySqlClient.MySqlCommand($sql,$conn)
$ds=New-Object system.Data.DataSet
$da=New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)
$da.fill($ds)
$conn.close()
$ds.tables[0]
I get a fatal error.
When I replace $sql by either
$sql = "SELECT DATABASE();"
or
$sql = "SELECT 1;"
I get the expected result.
I found this question, but it doesn't solve my problem.
I'm trying to port SQLIse (a part of the SQLPSX project ) to the MySQL version MySQLIse.
I want to process any simple valid mysql statements.
EDIT:
I was trying to run parts of the sakila-schema.sql the mysql demo database install script which runs by something like
mysql> SOURCE
C:/temp/sakila-db/sakila-schema.sql;
I found the solution in this blog
I have to add
;Allow User Variables=True
to the connection string:
$connectionstring = "Server=$Server;Port=$port;Database=$DataBase;Uid=$User;Pwd=$Password;allow zero datetime=yes;Allow User Variables=True"
works. I tested it with version 6.3.6.0. of MySql.Data.
Related
Im trying to run the following query against my mySQL database :
"INSERT INTO present (name) VALUES ('fred');"
I can run this query in the UI in PHPMyAdmin and it created the expected data, however, I can not run it from my PowerShell script. I can get data from the database using my PowerShell script, but can't seem to be able to create any. Any ideas ?
EDIT
Code I use to connect to database :
function ConnectToDatabase([string]$user, [string]$pass, [string]$MySQLHost, [string]$database) {
Log "--------"
Log "Connecting to database"
# Load MySQL .NET Connector Objects
[void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data")
# Open Connection
$connStr = "server=" + $MySQLHost + ";port=3306;uid=" + $user + ";pwd=" + $pass + ";database="+$database+";Pooling=FALSE"
try {
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
$conn.Open()
} catch [System.Management.Automation.PSArgumentException] {
Log "Unable to connect to MySQL server, do you have the MySQL connector installed..?"
Log $_
#Exit
} catch {
Log "Unable to connect to MySQL server..."
Log $_.Exception.GetType().FullName
Log $_.Exception.Message
#exit
}
Log "Connected to MySQL database : $MySQLHost\$database"
Log "--------"
return $conn
}
Running the query
$conn = ConnectToDatabase $user $pass $MySQLHost $database
$query = "INSERT INTO present (name) VALUES ('fred');"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand $query, $conn
I also had this to GET data from the database but I thought it was redundant to the Insert of data
$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$dataSet = New-Object System.Data.DataSet
$recordCount = $dataAdapter.Fill($dataSet, "data")
return $dataSet.Tables[0]
The code you posted creates a MySqlCommand object, but doesn't actually execute the SQL statement. Use the ExecuteNonQuery() method for that:
$conn = ConnectToDatabase $user $pass $MySQLHost $database
$query = "INSERT INTO present (name) VALUES ('fred');"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand $query, $conn
$Command.ExecuteNonQuery()
So I am attempting to connect to a database on an end device from one of my servers, however I'm getting the following error:
Can't connect to data source '<user>' because I can't work out what driver to use (it doesn't seem to contain a 'dbi:driver:' prefix and the DBI_DRIVER env var is not set) at <script> line 18
My lines of code are the following. I removed some private information of course.
my $sHDS = shift || "<host>";
my #rows;
my $cust = '<customer name>';
my $dsn = 'dbi:Sybase:' . $sHDS;
my $user = '<user>';
my $pass = '<password>';
my $hDb = DBI::connect($dsn, $user, $pass)
or die "Can not connect to ICM Database $DBI::errstr";
Anyone see where I am going wrong?
The correct call has the format
DBI->connect($dsn, $user, $password)
which is subtly but significantly different from
DBI::connect($dsn, $user, $password)
The first call is equivalent to the call
DBI::connect( 'DBI', $dsn, $user, $password )
and the connect function in DBI actually expects your dsn to be specified in the 2nd argument it receives.
Connect with mysql and retrive data from the table.
my $db ="JJusers";
my $user ="root";
my $password ="abcdef";
my $host ="localhost";
my $dbh =DBI->connect("DBI:mysql:$db:$host",$user,$password);
my $uDt = $dbh->prepare("select Username,Password from Users");
my $rv = $uDt->execute;
print "<script>alert($rv)</script>";
When I execute this code I am getting the result as 1. In database the data stored as:
1, jj, pp(SNO, USERNAME,PASSWORD)
Why isn't it getting the right data?
You are printing the result of execute, not the actual database results. You want to do something like this...
while (my #data = $rv->fetchrow_array()) {
my $username = $data[0];
my $password = $data[1];
// ...
}
->execute returns just query result(0, 1, 0E0), but not resultset.
As for me, best way is:
my $res = $dbh->selectall_arrayref('select Username,Password from Users', {Slice=>{}});
# now, you can iterate result.
# for example:
foreach my $row(#$res) {
print $row->{Username};
}
If you need bind vaiables, you can use selectall_arrayref also:
my $res = $dbh->selectall_arrayref('select Username,Password from Users where id = ?',
{Slice=>{}}, 1
);
I have written the following code in Perl. I have ActivePerl 5.14 for Windows 7.
#!C:\perl64\bin\perl.exe -wT
use strict;
use warnings;
use DBI;
print "Content-type: text/html \n\n";
# MYSQL CONFIG VARIABLES
my $driver = "mysql";
my $database = "test555";
my $tablename3 = "test77";
my $user = "root";
my $pw = "root";
# PERL MYSQL CONNECT()
my $dbh = DBI->connect("DBI:$driver:$database", $user, $pw,);
my $sth = $dbh->prepare("
SELECT *
FROM t6
WHERE paragraph='PWE1234'
");
$sth->execute();
#$dbh->disconnect;
#exit 0;
When the program reaches $dbh->disconnect, the system is throwing an error; hence commented it out. When I comment that out, the system is not throwing any error, but neither do I get output.
There is a result for this query, I checked with MySQL once separately.
There is no output because you have no code to create any output.
After calling execute you need to call one of the fetchsomething methods and do something with the data structure you get back.
I have a Powershell script that backs up my MySQL DB's each night using mysqldump. This all works fine but I would like to extend the script to update a reporting db (db1) from the backup of the prod db (db2). I have written the following test script but it does not work. I have a feeling the problem is the reading of the sql file to the CommandText but I am not sure how to debug.
[system.reflection.assembly]::LoadWithPartialName("MySql.Data")
$mysql_server = "localhost"
$mysql_user = "root"
$mysql_password = "password"
write-host "Create coonection to db1"
# Connect to MySQL database 'db1'
$cn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$cn.ConnectionString = "SERVER=$mysql_server;DATABASE=db1;UID=$mysql_user;PWD=$mysql_password"
$cn.Open()
write-host "Running backup script against db1"
# Run Update Script MySQL
$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql = Get-Content C:\db2.sql
$cm.Connection = $cn
$cm.CommandText = $sql
$cm.ExecuteReader()
write-host "Closing Connection"
$cn.Close()
Any assistance would be appreciated. Thanks.
This line:
$sql = Get-Content C:\db2.sql
Returns an array of strings. When that gets assigned to something expecting a string then PowerShell will concatenate the array of strings into a single string using the contents of the $OFS (output field separator) variable. If this variable isn't set, the default separator is a single space. Try this instead and see if it works:
$sql = Get-Content C:\db2.sql
...
$OFS = "`r`n"
$cm.CommandText = "$sql"
Or if you're on PowerShell 2.0:
$sql = (Get-Content C:\db2.sql) -join "`r`n"