r/visualbasic • • May 08 '18

VB.NET Help [VB.NET]Help with pushing changes back to a database

Alright so I'm working on a final project. I use

Me.LEVEL_INSTANCETableAdapter.Fill(Me.LevelsDataSet.LEVEL_INSTANCE)
Me.L_COLUMNSTableAdapter.Fill(Me.LevelsDataSet.L_COLUMNS)
Me.HIGH_SCORESTableAdapter.Fill(Me.LevelsDataSet.HIGH_SCORES)

On form load to grab info from the database. I make changes with queries and stored procedures.

LEVEL_INSTANCETableAdapter.UnlockLevel(intLevelNum)
HIGH_SCORESTableAdapter.UpdateHighScore(SCORE:=intScore, LvlID:=intLevelNum, PlayerName:=strName)

These execute just fine, I can see the changes they make elsewhere in my program. then the issue comes when I try to save back to the database. I use.

Me.Validate()
Me.LEVEL_INSTANCEBindingSource.EndEdit()
Me.HIGH_SCORESBindingSource.EndEdit()

Then use

Me.TableAdapterManager.UpdateAll(Me.LevelsDataSet)
Me.LEVEL_INSTANCETableAdapter.Update(Me.LevelsDataSet.LEVEL_INSTANCE)
Me.HIGH_SCORESTableAdapter.Update(Me.LevelsDataSet.HIGH_SCORES)

The data never goes back to the database (and if I understand the update method correctly, it returns a number that represents the number of rows changed, which for me, are always zero)

I have the dataset, tableadaptermanager, tableadapters, and binding navigators. my database and dataset's "copy to output dir" is set to "copy if newer"

I have also tried another method that starts with this

Dim NewHighScores As LevelsDataSet.HIGH_SCORESDataTable = CType(Me.LevelsDataSet.HIGH_SCORES.GetChanges(Data.DataRowState.Added), LevelsDataSet.HIGH_SCORESDataTable)
Dim ModifiedHighScores As LevelsDataSet.HIGH_SCORESDataTable = CType(Me.LevelsDataSet.HIGH_SCORES.GetChanges(Data.DataRowState.Modified), LevelsDataSet.HIGH_SCORESDataTable)

But it seems like getchanges in that line is showing no changes...

I've seen methods which directly interact with the database, ones that directly update, or calling on the database to run queries directly. I'd like to avoid those if possible. I'm really at my last legs here guys, I'll probably pass the class/assignment even if I don't get this working, but I'd like to understand it for the future... Thanks for all your responses in advance.

Edit: formatting

5 Upvotes

11 comments sorted by

2

u/JamesWjRose May 09 '18

Not the answer you are looking for, but....

Consider using stored procedures to send the data you want back to the database. I have been a db developer for 25+ years and I don't use Data Adapters, so my pov and extended history could be the "wrong" pattern.

I have long used stored procedures to insure that:

  1. There are distinct layers in the application

  2. This allows a level of security for the application as access to the abilities of the db is restricted to stored procedures only.

1

u/Jaco2point0 May 09 '18

Thanks so much for your answer. I will try this.

2

u/JamesWjRose May 09 '18

Stored procedures have great benefits, but learning them can take you some time. Just be aware

2

u/Jaco2point0 May 09 '18

I actually transferred in a bunch of credits and am taking courses out of order, so luckily I took databases last semester. Stored procedures don’t scare me so as long as google can help me figure out how to run them I’ll be fine.

2

u/JamesWjRose May 09 '18

One HUGE benefit, from a development side, is the separation of the layers. One place I worked had the SQL in the code, and the issue was a simple ORDER BY statement. I could have fixed, tested and moved the solution to production in under an hour if it had been a stored procedure, but since it was in the code MONTHS went by while other issued delayed the release.

1

u/Jaco2point0 May 10 '18

OK So i switched to using a stored procedure (for half of it). And the same issue is happening, the changes happen not to the database but only what seems to be the temporary copy the program makes.

        Dim SQLconnect As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Levels.mdf;Integrated Security=True")

        Dim SQLComand0 As New SqlCommand("Update LEVEL_INSTANCE SET UNLOCKED = 'TRUE' Where ID = " & intLevelNum, SQLconnect)
        Dim SQLComand1 As New SqlCommand("UpdateHighScores", SQLconnect)
        SQLComand1.CommandType = CommandType.StoredProcedure
        SQLComand1.Parameters.AddWithValue("@SCORE", intScore)
        SQLComand1.Parameters.AddWithValue("@LvlId", intLevelNum)
        SQLComand1.Parameters.AddWithValue("@PlayerName", strName)

        Try
            SQLconnect.Open()
            SQLComand0.ExecuteNonQuery()
            SQLComand1.ExecuteNonQuery()
            SQLconnect.Close()
        Catch ex As Exception
            MessageBox.Show("Error in updating database in " & Me.Name.ToString & " |" & ex.ToString)
        End Try

Does this at least look like I'm on the right track?

2

u/JamesWjRose May 10 '18

You look close, but this: Dim SQLComand0 As New SqlCommand("Update LEVEL_INSTANCE SET UNLOCKED = 'TRUE' Where ID = " & intLevelNum, SQLconnect)

You only need one SQLCommand, not the two. So SQLCommand0 should be deleted. I am hoping that "UpdateHighScores" has the parameters, if so that should work for you

Is not how you create a stored procedure. The stored procedure should take in the parameters, which you have added, take a looked at this example and about half way down there is a stored procedure you can see how to use.

1

u/Jaco2point0 May 10 '18

Yeah but it works, so I'm not really worried about it being a stored procedure vs just a command (query?). My issue is that the changes aren't going to the database proper, just to some temporary version of the database which gets thrown out, eventually.

I run the code, it all executes, the changes appear in the data within the program. But then if I close the program, and query the tables, none of the changes apply, at all. But then I restart the program, and the changes are still evident. It's bizarre.

If you wanna see the stored procedure that's being called here it is but it's really not the issue.

CREATE PROCEDURE [dbo].[UpdateHighScores]
	    @SCORE Integer,
	    @LvlID Integer,
	    @PlayerName Varchar(20)
AS
IF 10 <= (SELECT Count(ScoreID) FROM HIGH_SCORES WHERE LevelID = @LvlID) 
    IF @Score > (SELECT MIN(SCORE) FROM HIGH_SCORES WHERE LevelID = @LvlID)
	    UPDATE HIGH_SCORES SET SCORE = @SCORE, PlayerName = @PlayerName WHERE ScoreID = (SELECT MIN(SCOREID) FROM HIGH_SCORES WHERE SCORE IN (SELECT MIN(SCORE) AS T1 FROM HIGH_SCORES WHERE LEVELID = @LVLID))
    ELSE
	    RETURN
ELSE
    INSERT INTO HIGH_SCORES(LevelID, PlayerName, Score) VALUES(@LvlID,@PlayerName,@Score);
RETURN

It's not pretty but it does what I need. Idk, sorry if I sound rude I'm just frustrated.

2

u/JamesWjRose May 10 '18

I get frustration, it's ok . I'll have time tomorrow to take a peek.

1

u/Jaco2point0 May 10 '18

I appreciate it man.

2

u/JamesWjRose May 11 '18

re: frustrated.

Yea, welcome to the world of software development. Sometimes things just don't work. (arg!) I have been a developer for 20+ years, [source](http://www.blissgig.com), so yea sometimes it's frustrating. Sometimes it will be your fault, sometimes the computer/components. Sorry.

Anyway,

It seems your code is fine, but to be sure let's change the stored procedure a little bit

CREATE PROCEDURE [dbo].[UpdateHighScores]

@SCORE Integer,

@LvlID Integer,

@PlayerName Varchar(20)

AS

BEGIN

INSERT INTO HIGH_SCORES (LevelID, PlayerName, Score) VALUES (@LvlID, @PlayerName, @Score);

END

This way we can insure that data is being written to the database. (aside: consider a date/time field in your High_Scores table, you're likely to want to know when this happened)

So, let's do the following test

  • Update the proc

  • Run the application and the code that will update the score. Do **NOT** shut down the app.

  • I assume you are running SQL Server Manager, or some such tool. Query the database to see if your new values are there.

  • Shut down the application

  • Run the query again.

  • Start the app, does the data appear?

If you are finding that data is appearing in the app after shutdown and restart, then it FEELS that your SQL Manager tool might not be looking at the same db. Check your conenction string. Take a peek at this site for the connection best for you: https://www.connectionstrings.com/

Oh, and good morning