|
發表者 |
討論內容 |
冷日 (冷日) |
發表時間:2016/2/15 2:41 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15773
|
- [轉貼]MySQL and PowerShell
MySQL and PowerShellFrom vWiki To be able to interact with a MySQL database from PowerShell you need to have the MySQL .NET Connector installed first on the machine that you're going to run PowerShell from - http://dev.mysql.com/downloads/connector/net/ ConnectMake sure you have the .NET connector installed 1st - http://dev.mysql.com/downloads/connector/net/ function Connect-MySQL([string]$user,[string]$pass,[string]$MySQLHost,[string]$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" $conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr) $conn.Open() return $conn }
function Disconnect-MySQL($conn) { $conn.Close() }
So, for example... # Connection Variables $user = 'myuser' $pass = 'mypass' $database = 'mydatabase' $MySQLHost = 'database.server.com'
# Connect to MySQL Database $conn = Connect-MySQL $user $pass $MySQLHost $database
Improved connect function with error catcher... function ConnectMySQL([string]$user, [string]$pass, [string]$MySQLHost, [string]$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"
return $conn }
CommandsAll database operations are done through methods of the MySqlCommand object, the two methods of main interest are... - ExecuteNonQuery - Used for queries that don't return any real information, such as an INSERT, UPDATE, or DELETE.
- ExecuteReader - Used for normal queries that return multiple values. Results need to be received into
MySqlDataReader object. - ExecuteScalar - Used for normal queries that return a single. The result needs to be received into a variable.
Non-Query function Execute-MySQLNonQuery($conn, [string]$query) { $command = $conn.CreateCommand() # Create command object $command.CommandText = $query # Load query into object $RowsInserted = $command.ExecuteNonQuery() # Execute command $command.Dispose() # Dispose of command object if ($RowsInserted) { return $RowInserted } else { return $false } }
# So, to insert records into a table $query = "INSERT INTO test (id, name, age) VALUES (1, 'Joe', 33)" $Rows = Execute-MySQLNonQuery $conn $query Write-Host $Rows " inserted into database"
Reader QueryIn theory, this should work, but it doesn't seem to for me. There's something wrong with the while ($results.Read()) , in that you end up displaying the last row returned by the SQL query multiple times. Suspect its due to the way that a Reader object only seems to hold a result temporarily. $query = "SELECT * FROM subnets;" $cmd = $connMySQL.CreateCommand() $cmd.CommandText = $query $results = $cmd.ExecuteReader() $cmd.Dispose() while ($results.Read()) { for ($i= 0; $i -lt $reader.FieldCount; $i++) { write-output $reader.GetValue($i).ToString() } }
Instead, this approach seems to work more reliably. By loading the data into a dataset, it becomes available for offline manipulation and isn't reliant on the database once the data is loaded in. function Execute-MySQLQuery([string]$query) { # NonQuery - Insert/Update/Delete query where no return data is required $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $connMySQL) # Create SQL command $dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd) # Create data adapter from query command $dataSet = New-Object System.Data.DataSet # Create dataset $dataAdapter.Fill($dataSet, "data") # Fill dataset from data adapter, with name "data" $cmd.Dispose() return $dataSet.Tables["data"] # Returns an array of results }
# So, to produce a table of results from a query... $query = "SELECT * FROM subnets;" $result = Execute-MySQLQuery $query Write-Host ("Found " + $result.rows.count + " rows...") $result | Format-Table
Scalar Query function Execute-MySQLScalar([string]$query) { # Scalar - Select etc query where a single value of return data is expected $cmd = $SQLconn.CreateCommand() # Create command object $cmd.CommandText = $query # Load query into object $cmd.ExecuteScalar() # Execute command }
OtherTo perform other random commands that don't read or write data to/from a database... $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand("USE $database", $conn)
Basic escaping of text can be performed by... function Escape-MySQLText([string]$text) { [regex]::replace($text, "'", "\'") [regex]::replace($text, "\\", "\\") }
...you'd need to add additional cases to this to allow for string formats that you expect, there isn't an equivalent of PHP's mysql_real_escape_string() Test for NULLIn order to be able to test for a NULL value in a set of results from a query, you need to compare against a specific DB NULL value. Otherwise you can get errors similar to... Error: "Cannot convert the "0" value of type "System.Int32" to type "System.DBNull" Method invocation failed because [System.DBNull] doesn't contain a method named 'xxx'.
So to correctly test, use the following... if ([System.DBNull]::Value.Equals($db_query_result)) { Write-Host "Result is NULL" }
The above was sourced from http://blogs.technet.com/b/industry_insiders/archive/2008/09/15/testing-for-database-null-values-from-powershell.aspx 原文出處:MySQL and PowerShell - vWiki
|
|
冷日 (冷日) |
發表時間:2016/2/15 2:44 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15773
|
- [轉貼]PowerShell MySQL querie syntax
- PowerShell MySQL querie syntax
I want to insert Data in my MySQL Database by PowerShell. My Code is working, but I have a little problem with the varables in the insert string.
How can I use a variable in the insert string?
$cn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
$cn.ConnectionString = "SERVER=localhost;DATABASE=test;UID=root;PWD=pwd"
$cn.Open()
$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
#The problem, not working
$n = 7
$sql = 'INSERT INTO db1ea4test1.besitzer (besID, Vorname, Name) VALUES ( '$n' , "Testvor" + '$n' , "Testnach" + '$n')'
# Working
#$sql = 'INSERT INTO db1ea4test1.besitzer (besID, Vorname, Name) VALUES ("6", "Testvor", "Testnach")'
$cm.Connection = $cn
$cm.CommandText = $sql
$dr = $cm.ExecuteNonQuery()
mysql powershell powershell-v2.0 mysql-connector
Answer
Try using double quotes for sql string, single quotes around individual variables and ensuring your concatenated variables are quoted:
$sql = "INSERT INTO db1ea4test1.besitzer (besID, Vorname, Name) VALUES ( '$n' , 'Testvor$($n)' , 'Testnach$($n)')"
原文出處: PowerShell MySQL querie syntax - Stack Overflow
|
|
|
冷日 (冷日) |
發表時間:2016/2/21 7:36 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15773
|
- [轉貼]Database Queries with Windows Powershell
- Database Queries with Windows Powershell
I haven’t done a serious learning project for a while so this week I decided to play around with Windows Server 2008 and PowerShell. I’ll post some thoughts about Server 2008 soon (at first glance it looks terrific once you get past the fact that IIS is now a "role" instead of something you install). But I wanted to post a PowerShell example first because I wanted to do something with it that I couldn’t find information about anywhere — specifically, perform a database query and dump the contents to the console. (Later we’ll get fancy and dump it to HTML or send it somewhere via email, etc.)
PowerShell can invoke any .NET object, so I knew it was possible to do database stuff with a PowerShell script, but I couldn’t find any examples anywhere, so here’s what I cooked up via trial and error.
The first step is to create a database connection:
[system.reflection.assembly]::LoadWithPartialName("MySql.Data")
$cn = New-Object -TypeName MySql.Data.MySqlClient.MySqlConnection
The syntax to load a .NET assembly in PowerShell is pretty awkward; couldn’t they have provided a Get-Assembly cmdlet? (I suspect that thousands of PowerShell users have already written that one already.) Also, you have to know the assembly name of your ADO.NET provider (which, for MySql, is "MySql.Data," not "MySql.Data.MySqlClient," which was my first guess). The thing to remember is that loading an assembly is syntactically different than including a namespace even though the objective is sort of the same.
Fortunately this is the only part of the process that I didn’t get right the first time, and I had it resolved after a few minutes of experimentation.
I should mention that I’m using the MySql data provider because we use MySql on Approver.com, but you can obviously use any ADO.NET provider you want here. This assumes that your ADO.NET provider is installed in the GAC; if you need to make an explicit reference to an assembly in the file system the syntax is different.
Next, open the database connection:
$cn.ConnectionString = "SERVER=localhost;DATABASE=mydb;UID=xxx;PWD=yyy"
$cn.Open()
If you want, you can check the value of $cn.State here to make sure it worked. Then execute the query:
$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql = "SELECT ID, FirstName, LastName FROM Person LIMIT 50"
$cm.Connection = $cn
$cm.CommandText = $sql
$dr = $cm.ExecuteReader()
ADO.NET programmers know that there are lots of ways to do this that require fewer lines of code, but I like to assign everything out explicitly using properties of the ADO.NET Connection and Command objects.
Finally we iterate over the results and close the connection:
while ($dr.Read())
{
write-host $dr.GetInt32(0) " " $dr.GetString(1) " " $dr.GetString(2)
}
$cn.Close()
This is not too different than what a C# developer is accustomed to, particularly reading out the data. I like that you can just pass a big list of values to write-host without having to explicitly concatenate or convert to strings here. PowerShell figures out what you want to do and does the right thing.
On Approver.com we have a bunch of utilities that we use to monitor system health and site activity (like how many people registered that day, whether people are discovering and using certain features of the site, etc.). Every web site should crunch these numbers frequently (otherwise you have no idea whether the work you’re doing matters to your users).
I think I’m going to eventually migrate our various statistical and maintenance utilities to Powershell. The power of the .NET framework combined with the convenience of script is going to come in handy for a lot of stuff.
原文出處:Database Queries with Windows Powershell | Jeffrey McManus
|
|
|