Hi,

I'm doing an app that adds info to a MySQL BD

Imports MySql.Data.MySqlClient

Public Class curso_add
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "Ficheiros de Imagem |*.jpg;*.bmp;*.png;*.gif"
        OpenFileDialog1.FilterIndex = "2"
        OpenFileDialog1.Title = "Escolha uma imagem..."
        OpenFileDialog1.InitialDirectory = "C:\"
        OpenFileDialog1.ShowDialog()
    End Sub

    Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
        Dim erro As System.IO.Stream
        Try
            OpenFileDialog1.CheckFileExists = True
            OpenFileDialog1.ShowReadOnly = False


            erro = OpenFileDialog1.OpenFile()

            imagem_box.Text = OpenFileDialog1.FileName.ToString
            PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)

            If Not (erro Is Nothing) Then
                erro.Close()
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim con As New MySqlConnection("Server=localhost;Database=escola_musica;Uid=root;Pwd=;")
        Dim sql As String = "INSERT INTO cursos(nome_curso, imagem_curso, nro_max_aluno) VALUES ('" & TextBox1.Text & "', '" & imagem_box.Text & "', '" & TextBox2.Text & "')"

        Dim cmd As New MySqlCommand(sql, con)

        con.Open()

        Dim x As Integer = cmd.ExecuteNonQuery()

        If x < 1 Then
            MessageBox.Show("Erro ao inserir", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            MessageBox.Show("Registo inserido com sucesso!", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Gestão_Prof.Show()
            Me.Close()
        End If

        con.Close()
        cmd = Nothing
    End Sub
End Class

but in the image path doesn't appear the slashes

Dani AI

Generated

Brief summary: the missing backslashes came from inserting a raw Windows path into an SQL literal. was concatenating the FileName straight into the command text, and ’s quick fix (escaping the backslashes before insert) made the stored value look right. That workaround is valid, but the safer, correct approach is to use parameterized commands so the connector sends the path as data (no manual escaping needed) and to avoid SQL injection.

Why this happens: when a value is embedded inside a SQL string literal, the database parser treats backslash as an escape character; a single backslash can be consumed or interpreted as an escape sequence. Doubling the backslashes encodes a single literal backslash inside the SQL literal, which is why the Replace approach fixed the symptom.

Recommended fix (VB.NET + MySQL): send the filename as a parameter instead of building SQL by string concatenation.

Dim sql = "INSERT INTO cursos (nome_curso, imagem_curso, nro_max_aluno) VALUES (@nome, @imagem, @nro)"
Using con As New MySqlConnection("Server=localhost;Database=escola_musica;Uid=root;Pwd=;")
  Using cmd As New MySqlCommand(sql, con)
    cmd.Parameters.AddWithValue("@nome", TextBox1.Text)
    cmd.Parameters.AddWithValue("@imagem", imagem_box.Text)
    cmd.Parameters.AddWithValue("@nro", Integer.Parse(TextBox2.Text))
    con.Open()
    cmd.ExecuteNonQuery()
  End Using
End Using

Extra tips and checks: confirm the DB column is a text type (VARCHAR/TEXT) and inspect the stored value with a DB client (not the app) to see raw characters. If absolute filesystem paths are being stored consider storing filenames or relative paths and reconstructing the full path at runtime. Parameterized queries fix escaping and are preferable to manual Replace-based fixes.

Recommended Answers

All 9 Replies

someone help me, please?

I presume the image path is stored in the field imagem_box.Text

are you saying that when you execute the insert command the data in column imagem_curso does not contain the forward slashes

I presume the image path is stored in the field imagem_box.Text

are you saying that when you execute the insert command the data in column imagem_curso does not contain the forward slashes

Yes, you can see what is happening right here

I had a similar problem coding in MS Access you might like to try using two slashes on the input i.e.

f:\\pap\\siteimages\\curso\\drum.jpg

you can put it in manually first to test, then if that is the problem, change your code to insert the second slash programmatically

I had a similar problem coding in MS Access you might like to try using two slashes on the input i.e.

f:\\pap\\siteimages\\curso\\drum.jpg

you can put it in manually first to test, then if that is the problem, change your code to insert the second slash programmatically

Problem solved, now can you help me insert the second slash in the path? Isn't it a little bit complicated?

check out the string.replace method. eg

newstring = imagem_box.Text.replace("\","\\")

I haven't tested it, (don't have a .net environment with me at the moment)

check out the string.replace method. eg

newstring = imagem_box.Text.replace("\","\\")

I haven't tested it, (don't have a .net environment with me at the moment)

Thanks man, it's working perfectly. ;)

By the way, do you know why does it happen? Because it's really weird :S

no it took ages for me to work out what the problem was.

damn, what a patience :S

One more time than you, a lot ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.