Powershell connection to MySQL

Source: Internet
Author: User

Generally, powershell directly uses invoke-sqlcmd to connect to SQL Server. This is convenient, but sometimes you still need to connect to other databases, such as MySQL.

Here is a summary of powershell connection to MySQL:

Connecting to MySQL is through the. NET Framework, so you must first install mysql. Net connector (http://dev.mysql.com/downloads/connector/net)

If you do not want to install mysql. Net connector, you can copy it directly on other installed machines.MySQL. Data. DLL to the desired machine.

Connection method:

If mysql. Net connector is installed

 
[Void] [system. reflection. Assembly]: loadwithpartialname ("MySQL. Data")

If you use the mysql. Data. dll file directly

$ Mysqldatadll="C: \ scripts \ mysql. Data. dll"[Void] [system. reflection. Assembly]: Loadfrom ($ Mysqldatadll)

After reading the DLL, we can process it:

 $ Connectionstr = "  Server = 192.168.1.1; uid = user; Pwd = user123; database = mydb;  "  $ Querysql = "  Select MSG from messages limit 1;  " $ Connection = New- Object mysql. Data. mysqlclient. mysqlconnection  $ Connection . Connectionstring = $ Connectionstr  $ Connection  . Open ()  $ Command = New-object mysql. Data. mysqlclient. mysqlcommand ( $ Querysql , $ Connection  )  $ Dataadapter = New-object mysql. Data. mysqlclient. mysqldataadapter ( $ Command )  $ Dataset = New- Object System. Data. Dataset  $ Recordcount = $ Dataadapter . Fill ( $ Dataset  )  $ Dataset . Tables [0]

Here we will get a system. data. dataSet object. We use tables [0] To return 0th table sets. This can already return the dataset we need, but if we want to further process the row set:

$ Table=$ Dataset. Tables [0]Foreach($ Row In $ Table. Rows ){$ Row. MSG}

 

If you want to know the number of columns in this table, you can use the following method:

 
$ Table. Columns | format-table

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.