PowerShell MySQL query syntax
I want to insert data into my MySQL database using PowerShell.
My code is working, but I have a little problem with the variables in the insert string.
How can I use a variable in the insert string?
[system.reflection.assembly]::LoadWithPartialName("MySql.Data")
$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()
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)')"
精彩评论