开发者

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)')"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜