创建 PowerShell 连接字符串 [英] Creating a PowerShell Connection String

查看:62
本文介绍了创建 PowerShell 连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个 ConnnectionString,它允许我使用 PowerShell 连接到我的本地数据库.下面是我的代码:

I have been trying to create a ConnnectionString that will allow me to connect to my local database using PowerShell. Below is my code:

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=localhost;Database=test;Uid=<username here>;Pwd=<password here>;"
$conn.Open()
$sql = "SELECT EMP_STATUS FROM test_table"
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)
$rdr = $cmd.ExecuteReader()
while($rdr.Read())
{
    $test = $rdr["EMP_STATUS"].ToString()
}
Write-Output $test

但是,我不知道我做错了什么,并且已经拉了很长一段时间的头发.谁能帮我弄清楚我在 ConnectionString 中做错了什么?

However, I have NO CLUE what I am doing wrong and have been pulling my hair out for quite some time. Can anyone help me figure out what I am doing wrong in the ConnectionString?

谢谢大家!!

我意识到我的第一个问题是我有 MySQL 数据库,而不是 SQL 数据库.因此,我将不得不使用不同的方法进行连接.这正是我需要你帮助的地方!!到目前为止,我已将代码修改如下:

I realized that my first problem was that I have MySQL database, not SQL database. As a result, I will have to connect using a different method. This is exactly where I need your help!! So far I have modified my code as follows:

[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection

$connString = "server=localhost;port=3306;uid=<username here>;pwd=<password here> ;database=test;"
$conn.ConnectionString = $connString
$conn.Open()
$sql = "SELECT EMP_STATUS FROM test_table"
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql,$conn)
$rdr = $cmd.ExecuteReader()
$test = @()
while($rdr.Read())
{
    $test += ($rdr["EMP_STATUS"].ToString())
}
Write-Output $test

但是,这里还有几个问题:1)如何使用MySQL .NET连接工具连接本地MySQL数据库?2) 这个 PowerShell 脚本应该保存在哪里?3) 我还需要做其他更改吗?

However, here are a few more questions: 1) How do you use the MySQL .NET connection tool to connect to a local MySQL database? 2) Where should this PowerShell script be saved? 3) Are there any additional changes I should make?

非常感谢

推荐答案

试试这个:

$conn.ConnectionString = "Server=localhost;Database=test;User ID=<username here>;Password=<password here>;"

然后 $test 只给你在选择中找到的最后一个值!要让 $test 包含 select 中的所有值,请像这样更改您的代码:

then $test give you only the last value found in the select! To have $test containing all value from select change your code like this:

$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=localhost;Database=test;User ID=<username here>;Password=<password here>;"
$conn.Open()
$sql = "SELECT EMP_STATUS FROM test_table"
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)
$rdr = $cmd.ExecuteReader()
$test = @()
while($rdr.Read())
{
    $test += ($rdr["EMP_STATUS"].ToString())
}
Write-Output $test

这篇关于创建 PowerShell 连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆