gpt4 book ai didi

mysql - 无法使用 Powershell 对 mySQL 数据库运行插入查询,但可以通过 PHPMyAdmin UI

转载 作者:行者123 更新时间:2023-11-29 10:21:07 24 4
gpt4 key购买 nike

我正在尝试对我的 mySQL 数据库运行以下查询:

"INSERT INTO present (name) VALUES ('fred');"

我可以在 PHPMyAdmin 的 UI 中运行此查询,它创建了预期的数据,但是,我无法从 PowerShell 脚本运行它。我可以使用 PowerShell 脚本从数据库获取数据,但似乎无法创建任何数据。有什么想法吗?

编辑

我用来连接数据库的代码:

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
}

运行查询

$conn = ConnectToDatabase $user $pass $MySQLHost $database
$query = "INSERT INTO present (name) VALUES ('fred');"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand $query, $conn

我也用它从数据库获取数据,但我认为这对于插入数据来说是多余的

$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$dataSet = New-Object System.Data.DataSet
$recordCount = $dataAdapter.Fill($dataSet, "data")
return $dataSet.Tables[0]

最佳答案

您发布的代码创建了一个 MySqlCommand 对象,但实际上并不执行 SQL 语句。使用ExecuteNonQuery()方法:

$conn = ConnectToDatabase $user $pass $MySQLHost $database
$query = "INSERT INTO present (name) VALUES ('fred');"
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand $query, $conn
$Command.ExecuteNonQuery()

关于mysql - 无法使用 Powershell 对 mySQL 数据库运行插入查询,但可以通过 PHPMyAdmin UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49234289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com