Question : VB:NET MSSQL problem write "strings" InsertCommand

Hello I have some problem when I write to data bas.

i have MSSQL 2008 where I have made a tabel.
The column is mixed with strings and int.

I collect som data from a OPC server then I write it down to the databas.


And the columms I´m tries to write in is declared "nchar(30)" so It should be OK. (I only write 3 letters max..)

This is my code.

Dim MSSQLquery As String = XMLData.TestTemplate01()  ///  This is my SQL question... in a XML file... looks lite this...  
INSERT INTO TEST(ProduktNr,ProdNamn) values({TEST.ProduktNr},{TEST.ProdNamn}

Maybe my problem is the "InsertCommand" maybe I can´t write with that.. only   int?




Dim conn As SqlConnection
        Dim sqladp As New SqlDataAdapter
        Dim mssqlq As String
        Dim sqlcmd As New SqlCommand
        Dim ConnectionstringSQL As String
        Dim MSSQLquery As String = XMLData.TestTemplate01()

        For Each item As KeyValuePair(Of String, OPCItem) In plcValues
            Dim shortValue As String = item.Value.Value

            MSSQLquery = MSSQLquery.Replace("{" & item.Key & "}", shortValue)
        Next

ConnectionstringSQL = "Data Source=127.0.0.1;Initial Catalog=Test;User Id=test;Password=test;"
        conn = New SqlConnection(ConnectionstringSQL)

        mssqlq = "" + MSSQLquery + ""
        Try
            conn.Open()
            sqladp.InsertCommand = New SqlCommand(mssqlq, conn)
            sqladp.InsertCommand.ExecuteNonQuery()

            MsgBox("Skrivit till MSSQL..")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

Answer : VB:NET MSSQL problem write "strings" InsertCommand

Strings need to be surrounded by single-quotes:

Try this:
INSERT INTO H20(ProduktNr,ProdNamn) Values (66,'TEST')

Then you need to make changes  to your code to detect strings and add the single quotes.

Any single quotes WITHIN the string need to be escaped with an additional single string (e.g. if you want to insert TEST'S OK

INSERT INTO H20(ProduktNr,ProdNamn) Values (66,'TEST''S OK')
Random Solutions  
 
programming4us programming4us