Results 1 to 25 of 25

Thread: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/2018

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/2018

    I have been following a tutorial and listening to what the guy says and then writing the code out for myself, blind. I run the code and there's no errors but nothing happens.


    Module1
    Code:
                
    Module Module1
    
        Sub Main(title As String)
            Dim server As New Server
            server.createDataBase()
            server.insertUsername(title)
        End Sub
    
    End Module
    Main

    Code:
    Imports System.Data.SQLite
    
    
    Public Class frmAdd
        Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
    
            ''Allow usr to choose image
            OpenFileDialog1.InitialDirectory = "C:/"
            OpenFileDialog1.Title = "Please choose a photo."
            OpenFileDialog1.Filter = "JPEG files (*.jpg)|*.jpg|GIF files (*.gif)|*.gif|All files (*.*)|*.*"
            OpenFileDialog1.ShowDialog()
    
            ''Open image in picturebox
            PictureBox1.BackgroundImage = Image.FromFile(OpenFileDialog1.FileName)
    
        End Sub
    
        Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    
            Dim title As String = Trim(txtName.Text)
            Dim genus As String = Trim(txtGenus.Text)
            Dim species As String = Trim(txtSpecies.Text)
            Dim common As String = Trim(txtCommon.Text)
            Dim picture As Image = PictureBox1.BackgroundImage
    
            ''create database
    
            Dim location As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            Dim fileName As String = "myDataBase.db"
            Dim fullpath As String = System.IO.Path.Combine(location, fileName)
            Dim connectionString As String = String.Format("Data Source = {0}", fullpath)
    
            If Not duplicateDatabase(fullpath) Then
    
                Dim createTable As String = "CREATE TABLE `Tarantulapp-DB` (
    	                                                       `Name`	TEXT,
    	                                                      `Genus`	TEXT,
    	                                                    `Species`	TEXT,
    	                                                 `CommonName`	TEXT,
    	                                                `Temperament`	TEXT,
    	                                               `VenomPotency`	TEXT,
    	                                                        `Sex`	TEXT,
    	                                                   `LastMolt`	DATE,
    	                                                   `LastFeed`	DATE,
    	                                                `LastHoming`	DATE,
                                            	`AverageTemperature`	INTEGER,
    	                                           `AverageHumidity`	INTEGER,
    	                                                     `Notes`	TEXT
                                                                            );"
    
    
                Using SQLconn As New SQLiteConnection(connectionString)
                    Dim cmd As New SQLiteCommand(createTable, SQLconn)
                    SQLconn.Open()
                    cmd.ExecuteNonQuery()
                End Using
    
            End If
    
        End Sub
    
        Public Sub InsertUsername(title As String, connectionstring As String, location As String)
    
            Try
    
            Catch ex As Exception
    
    
                Using sqlconn As New SQLiteConnection(connectionstring)
                    Dim insertUserQuery As String = "INSERT INTO TarantulappDB(Name) VALUES(@title)"
                    Dim cmd As New SQLiteCommand(insertUserQuery, sqlconn)
                    cmd.Parameters.AddWithValue("@title", title)
                    sqlconn.Open()
                    cmd.ExecuteNonQuery()
    
    
                End Using
            End Try
        End Sub
        Private Function duplicateDatabase(fullpath As String) As Boolean
    
            Return System.IO.File.Exists(fullpath)
    
        End Function
    
    End Class
    I edited an existing thread soi I wasn't spamming.
    Last edited by StealthyCat; Apr 28th, 2018 at 06:22 AM.

  2. #2
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,138

    Re: I can't see why this won't Work - Adding Data to SQL Database

    Function 'insertUsername' doesn't return a value on all code paths.
    When given errors like this, it is very important to read the error given. In this case the error outlines exactly what the issue is.

    You have defined a Function. A Function needs to return a value. You have no Return statement. For the record, you also haven't defined a return type.

    It isn't clear from what you've posted if there is a need to return a value or not, and since you didn't include any links to this Youtube video you are working off of its impossible to tell what their intent is as well.

    Assuming there is no need to return a value (such as whether or not this insert was successful or failed), then the fix to this specific error should be to change the word "Function" to "Sub". If the intent is to return a value, then you need a Return statement in the Function.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database

    Quote Originally Posted by OptionBase1 View Post
    When given errors like this, it is very important to read the error given. In this case the error outlines exactly what the issue is.

    You have defined a Function. A Function needs to return a value. You have no Return statement. For the record, you also haven't defined a return type.

    It isn't clear from what you've posted if there is a need to return a value or not, and since you didn't include any links to this Youtube video you are working off of its impossible to tell what their intent is as well.

    Assuming there is no need to return a value (such as whether or not this insert was successful or failed), then the fix to this specific error should be to change the word "Function" to "Sub". If the intent is to return a value, then you need a Return statement in the Function.
    Thanks for the help, man. It doesn't need to return a function so I will go and change that now. I did read the error but I'm very nooby and couldn't quite figure it out. Thank you!

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database

    I highlighted the wrong error:

    Severity Code Description Project File Line Suppression State
    Error BC30311 Value of type 'MySqlConnection' cannot be converted to 'SQLiteConnection'. Tarantulapp v 1.0 C:\Users\taran\source\repos\Tarantulapp v 1.0\Tarantulapp v 1.0\frmAdd.vb 92 Active

  5. #5
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,138

    Re: I can't see why this won't Work - Adding Data to SQL Database

    Again, read the error message and look at your code.

    You are declaring SQLconn as a MySqlConnection object, but then trying to use that connection object in a SQLiteCommand object.

    While I've never used either one, I'm fairly certain that MySQL and SQLite are two completely separate database systems. Not knowing which one you are using, I can't tell you how to fix it other than to say don't mix them like this. You need to declare objects related to the database system you are using.

  6. #6

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database

    Quote Originally Posted by OptionBase1 View Post
    Again, read the error message and look at your code.

    You are declaring SQLconn as a MySqlConnection object, but then trying to use that connection object in a SQLiteCommand object.

    While I've never used either one, I'm fairly certain that MySQL and SQLite are two completely separate database systems. Not knowing which one you are using, I can't tell you how to fix it other than to say don't mix them like this. You need to declare objects related to the database system you are using.
    Thanks once again. I have been following this tut and don't understand why he has no errors and I do haha.

  7. #7
    Frenzied Member
    Join Date
    Dec 2014
    Location
    VB6 dinosaur land
    Posts
    1,191

    Re: I can't see why this won't Work - Adding Data to SQL Database

    Quote Originally Posted by StealthyCat View Post
    Thanks once again. I have been following this tut and don't understand why he has no errors and I do haha.
    There's no way the tut would have compiled as you had it written so he either misspoke/typed or you misheard/read.

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,039

    Re: I can't see why this won't Work - Adding Data to SQL Database

    I think that the only way you could have gotten as far as that first error is if you have Option Strict OFF. That's the default setting, and one that can seem pretty useful when you are starting out. After all, if you turn it to ON, you are quite likely to find a whole bunch of errors that weren't there before. However, those are real errors. With Option Strict OFF, the compiler will make do, as best it can, with what you give it. Quite often, it will do the right thing, but when it doesn't, it'll be much harder to figure out why not. With Option Strict ON, having a function without a return value would be an error, so you'd never get far...though maybe as far as you had already gotten. In any case, you'd have gotten a more correct error message, which would have been helpful.

    Another point about Option Strict is that the code is more efficient, though you'll normally never see that. You write the same with Option Strict ON or OFF. Good code is good code, either way. What you can do with Option Strict OFF is not so good code, you just don't get scolded when you write it. Therefore, Option Strict ON just makes you better by not allowing you to be sloppy in some ways that you shouldn't be sloppy in. You can turn Option Strict ON for the project under Project | Properties on the Compile tab. You can also set it to default to On in the Tools | Options menu (but you have to find it, cause I always forget where it's located).

    So, you might wonder why Option Strict is OFF if it makes you a better coder, and the code is more efficient? Heck, why do you need it at all? You need to be able to turn Option Strict OFF for the rare cases where you have to use late binding. As to why it defaults to off, my best guess is that MS thought it would make coding appear easier. It does. Up front, it appears easier....until you find a bug that having Option Strict OFF allowed through, cause those can be a real joy to track down. After all, the code works...after a fashion, it just didn't do what you thought it should do.
    My usual boring signature: Nothing

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database

    Quote Originally Posted by Shaggy Hiker View Post
    So, you might wonder why Option Strict is OFF if it makes you a better coder, and the code is more efficient? Heck, why do you need it at all? You need to be able to turn Option Strict OFF for the rare cases where you have to use late binding. As to why it defaults to off, my best guess is that MS thought it would make coding appear easier. It does. Up front, it appears easier....until you find a bug that having Option Strict OFF allowed through, cause those can be a real joy to track down. After all, the code works...after a fashion, it just didn't do what you thought it should do.
    I suspect that making VB.NET more like VB6 by default was a factor too. Code being upgraded from VB6 would so often light up with Option Strict On.

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Thanks for your advice, guys. It's always appreciated. I have taken the stabalizers off and running on option strict ON. However, after fixing some of the code I have no errors now but it just won't do what it's suppoosed to. I have executed the SQL query in DB Browser and it works fine.
    Last edited by StealthyCat; Apr 28th, 2018 at 06:32 AM.

  11. #11
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Quote Originally Posted by StealthyCat View Post
    I have taken the stabalizers off and running on option strict OFF.
    Do you mean Option Strict On?
    Quote Originally Posted by StealthyCat View Post
    THowever, after fixing some of the code I have no errors now but it just won't do what it's suppoosed to.
    Then show us the code you have now and explain what it does do and how that differs from your expectation.

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Quote Originally Posted by jmcilhinney View Post
    Do you mean Option Strict On?

    Then show us the code you have now and explain what it does do and how that differs from your expectation.
    Yes, sorry. I meant on. I updated the OP with my current code. It creates a table and then SHOULD pass the title variable to the database (I am only doing it with one value until I can get it working.

  13. #13
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Do you see the issue here?
    Code:
        Public Sub InsertUsername(title As String, connectionstring As String, location As String)
    
            Try
    
            Catch ex As Exception
    
    
                Using sqlconn As New SQLiteConnection(connectionstring)
                    Dim insertUserQuery As String = "INSERT INTO TarantulappDB(Name) VALUES(@title)"
                    Dim cmd As New SQLiteCommand(insertUserQuery, sqlconn)
                    cmd.Parameters.AddWithValue("@title", title)
                    sqlconn.Open()
                    cmd.ExecuteNonQuery()
    
    
                End Using
            End Try
        End Sub
    Under what circumstances will that database code get executed? Hint: it won't. This is why you need to debug your code. If you had done then it would have been obvious that the code wasn't even being executed so it couldn't be failing.

  14. #14

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    I don't understand why not though. This is why I posted the thread, dude.

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    What is the purpose of a Try block? What is the purpose of a Catch block? If you don't know, you should read up on that because you need to understand exception handling if you're going to implement it. If you do know then you know why your code isn't being executed.

  16. #16
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,930

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    When you have a Try-Catch block, the code inside the Try section will run, and the code inside the Catch section will only run if an error (exception) happens in the Try section.

    In this case you have no code inside the Try section, so it cannot generate an exception, so the code inside the Catch block will not run.

    Quote Originally Posted by StealthyCat View Post
    I updated the OP with my current code.
    Please don't do that, it creates confusion and doesn't actually provide any benefit - it is better to post new information in new posts (unless you realise you missed something just after posting, and there are no more replies yet).

  17. #17

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Quote Originally Posted by si_the_geek View Post
    When you have a Try-Catch block, the code inside the Try section will run, and the code inside the Catch section will only run if an error (exception) happens in the Try section.

    In this case you have no code inside the Try section, so it cannot generate an exception, so the code inside the Catch block will not run.

    Please don't do that, it creates confusion and doesn't actually provide any benefit - it is better to post new information in new posts (unless you realise you missed something just after posting, and there are no more replies yet).
    Understandable. I don't know why I never saw that. I added that detering from the tutorial. I fixed it and still nothing happens. No messageboxes show.

    Code:
     Try
                Using sqlconn As New SQLiteConnection(connectionstring)
                    Dim insertUserQuery As String = "INSERT INTO TarantulappDB(Name) VALUES(@title)"
                    Dim cmd As New SQLiteCommand(insertUserQuery, sqlconn)
                    cmd.Parameters.AddWithValue("@title", title)
                    sqlconn.Open()
                    cmd.ExecuteNonQuery()
                    MessageBox.Show("Your entry has been added to the database!")
                End Using
    
            Catch ex As Exception
    
                MessageBox.Show("Failed to add the entry to the database!")
    
            Finally
    
                MessageBox.Show("Completed!")
    
            End Try

  18. #18
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    You appear to be calling Server.insertUsername and expecting frmAdd.InsertUsername to be executed. Again, debug your code. We keep pointing things out that you should already know because you should have debugged the code. Place breakpoints in appropriate places and step through the code. If you don't know how to debug (which you probably should have mentioned by now, if that's the case) then you should starting learning here:

    https://msdn.microsoft.com/en-us/lib...or=-2147217396

  19. #19

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Quote Originally Posted by jmcilhinney View Post
    You appear to be calling Server.insertUsername and expecting frmAdd.InsertUsername to be executed. Again, debug your code. We keep pointing things out that you should already know because you should have debugged the code. Place breakpoints in appropriate places and step through the code. If you don't know how to debug (which you probably should have mentioned by now, if that's the case) then you should starting learning here:

    https://msdn.microsoft.com/en-us/lib...or=-2147217396
    To be honest, I never even knew debuggin went any further than hitting F5 to run the code. I am guessing with this one, I have bitten off far more than I can chew as of yet but I have came to far to just abandon it.

    Do you mean calling frmAdd.InsertUsername in the module?



    I am so sorry for my noobiness on this. I will check out that article now.

  20. #20
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    If the method you want to call is in frmAdd then yes, you have to call the method on an instance of frmAdd, not on an instance of Server. If the InsertUsername method in frmAdd is the one you want to execute and it has three parameters then you need to pass three arguments to it when you call it. If it expects values for 'title', 'connectionString' and 'location' then you need to pass those values when you call it.

    Maybe that method shouldn't be part of the form at all. Maybe you should have a form at all. It's hard to say. You've got a module with a Main method that doesn't call Application.Run, which is usually the case only for Console applications, not WinForms applications.

  21. #21

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Thanks for your continued patience. I (think) I have fixed the module. I was forgetting to pass the parameters to the module while adding them to frmAdd.insertUsername.

    Code:
    Module Module1
    
        Sub Main(title As String, location As String, connectionstring As String)
            Dim server As New Server
            server.createDataBase()
            frmAdd.InsertUsername(location, title, connectionstring)
            Application.Run()
        End Sub
    
    End Module
    I am guessing I have made my biggest mistake for following a tutorial that was for a console app and not for a Windows Form app. I did try and find one, but all I could see was "tutorials" that are just someone doing it with crap music in the background (I don't feel that merely copying someone coding helps. It always helps to know a little of what's going on, IMHO).

    I have adapted my module a little to no avail. I wish I found a decent tutorial based on my needs before diving in.

  22. #22
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Why use a module at all? Just create a WinForms app, have the user enter data into TextBoxes and then execute your code in the Click event handler of a Button. You can handle a Button Click, get those three values from TextBoxes and/or My.Settings and pass them on to the method from already inside the form.

  23. #23

    Thread Starter
    Junior Member
    Join Date
    Sep 2017
    Posts
    26

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    Quote Originally Posted by jmcilhinney View Post
    Why use a module at all? Just create a WinForms app, have the user enter data into TextBoxes and then execute your code in the Click event handler of a Button. You can handle a Button Click, get those three values from TextBoxes and/or My.Settings and pass them on to the method from already inside the form.
    I'm sorry, I'm getting really confused here. Do you mean add that module code to the button code? It tells me server is not defined.

  24. #24
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,344

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    I think that you should start again with a new project. There's obviously stuff there that's irrelevant to what you're trying to do. Do as I suggested and create a Windows Forms Application project. Add appropriate controls for the user to enter the required data and add a Button to be clicked to initiate the data access code. In the Click event handler of the Button, gather the required data and call the method that performs the data access.

  25. #25
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,039

    Re: I can't see why this won't Work - Adding Data to SQL Database - Update - 28/04/20

    I'd go with that, too. If you started with a tutorial on a console app, I'm not sure of all the things that might have to change to make it work right as a forms app. Console apps just aren't that common, so starting with a forms app will likely be better.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width