Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Inserting data to mysql database?

$
0
0

I'm pulling a string from a text file and splitting that string into 3 strings $filename, $date, $time. Then I'm trying to insert those strings into a database.

$query = 'INSERT INTO page (filename,date,time) VALUES ($filename,$date,$time)'

If I do it this way I get:

Exception calling "ExecuteNonQuery" with "0" argument(s): "Unknown column '$filename' in 'field list'"

$query = 'INSERT INTO page (filename,date,time) VALUES ("$filename","$date","$time")'

If I do it this way I don't get errors but it inserts the string $filename, $date and $time into the database and not the strings that are inside of those variables. 

function ConnectMySQL([string]$user,[string]$pass,[string]$MySQLHost,[string]$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"
  $conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
  $conn.Open()
  $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand("USE $database", $conn)
  return $conn
}
function WriteMySQLQuery($conn, [string]$query) {
  $command = $conn.CreateCommand()
  $command.CommandText = $query
  $RowsInserted = $command.ExecuteNonQuery()
  $command.Dispose()
  if ($RowsInserted) {
    return $RowInserted
  } else {
    return $false
  }
}
 $strfiles = Get-Content C:\pdfoutLNJ.txt
 Foreach ($strfile in $strfiles){
 $comts = $strfile.Split(" ")
 $testb = $comts[0]

$filename = $comts[0]
$date = $comts[1]
$time = $comts[2]

if ($testb.startswith("NJ-")){
# setup vars
$user = 'root'
$pass = ''
$database = 'pagereport'
$MySQLHost = 'aspsvr49'
# Connect to MySQL Database
$conn = ConnectMySQL $user $pass $MySQLHost $database
# Read all the records from table
$query = 'INSERT INTO page (filename,date,time) VALUES ($filename,$date,$time)'
$Rows = WriteMySQLQuery $conn $query
Write-Host $Rows " inserted into database"
}
}



Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>