Storing information in the access database - sql

Hi I'm trying to store the information of a new element in the datagrid, In the app is open the information is there, but when we close it and open it again, all the new information dissapear, can someone help?
Dim cmdSql As String
'If txtNumero.Text = "1" Then
cmdSql = "INSERT INTO Fatura (Cliente, Data, ValorTotal) " &
"VALUES ('" & txtCliente.Text & "', #" &
dataFatura.Value.ToString("dd/MM/yyyy") & "#, " &
Replace(txtValorTotal.Text.ToString, ",", ".") & ")"
GerirLigacao.ExecutarCmdSQL(cmdSql)
cmdSql = "SELECT TOP 1 Numero FROM Fatura ORDER BY Numero DESC"
Dim r As DataSet = GerirLigacao.obterDados(cmdSql)
txtNumero.Text = r.Tables(0).Rows(0).Item("Numero")
txtNrFatura.Text = txtNumero.Text
Dim msg = "Fatura guardada com sucesso"
Dim titulo = "Guardar"
Dim botoes = MessageBoxButtons.OK
Dim icone = MessageBoxIcon.Information
MessageBox.Show(msg, titulo, botoes, icone)
Gerirligacao
Public Shared Sub ExecutarCmdSQL(ByVal comando As String)
Try
Dim cmdSql As New OleDbCommand(comando, ligacao)
cmdSql.ExecuteNonQuery()
Catch ex As Exception
Dim msg = "Aconteceu um erro de execução." & vbNewLine
Dim botoes = MessageBoxButtons.OK
Dim icone = MessageBoxIcon.Error
MessageBox.Show(msg & ex.Message, "ERRO", botoes, icone)
End Try
End Sub

Look for the database file in the Solution Explorer, click on it and in the Properties grid set Copy To Output Directory to Copy If Newer
More info: https://social.technet.microsoft.com/wiki/contents/articles/53248.visual-studio-copying-files-to-debug-or-release-folder.aspx
Now might also be a good time to tell you that you could make some serious improvements to your database access code; this way you're doing it makes things very hard work and the code is highly insecure (take a read of http://bobby-table.com for more info). Microsoft used to have a great set of walkthroughs at http://msdn2.microsoft.com/en-us/library/fxsa23t6(vs.80).aspx - that documentation has now been archived (being at least 15 years old) and I cant download them on a cellphone to check it "creating a simple data application" is still prt of it. There are a good number of tutorials on YouTube about how to use tableadapters and datasets if that's the route you want to use, though the modern technology (and widest spread of knowledge) these days is probably available for Entity Framework. Google for "getting started with entity framework" and take a look; I'd highly recommend you go this way than your existing route of using weakly typed datasets and direct sql queries

Related

How to add rows in an Access Table with parameters?

This is my function:
Function SQL_InsertUpdate(mySQLConnection As OleDbConnection, mySQLCommand As String, mySQLTable As String, mySQLTableColumns() As String, myParameters() As String)
Dim SQLCommand As OleDbCommand = New OleDbCommand(mySQLCommand, mySQLConnection)
Dim myStringConstruct = mySQLCommand & " " & mySQLTable & " ("
'==============
For Each item In mySQLTableColumns
myStringConstruct = myStringConstruct & item & ", "
Next
myStringConstruct = Strings.Left(myStringConstruct, Len(myStringConstruct) - 2)
myStringConstruct = myStringConstruct & ") VALUES ("
For i As Integer = 0 To mySQLTableColumns.Length - 1
myStringConstruct = myStringConstruct & "#" & mySQLTableColumns(i) & ", "
SQLCommand.Parameters.AddWithValue("#" & mySQLTableColumns(i), myParameters(i))
Next
myStringConstruct = Strings.Left(myStringConstruct, Len(myStringConstruct) - 2)
myStringConstruct = myStringConstruct & ")"
SQLCommand.ExecuteNonQuery()
End Function
This is how I call the function:
Dim myParameters() As String = ({myNewID.ToString, myUser.ToString, myDepartment.ToString, mySubsidiary.ToString, myTitle.ToString, myRecurrence.ToString, myImpact.ToString, myTimeSaved.ToString, myPriority.ToString, myStatus.ToString, myTechnology.ToString, myDeveloper.ToString, myCostSave.ToString, myDescription.ToString, myCommentary.ToString, myDateSubmitted.ToString, myDateModified.ToString, myInReviewDate.ToString, myManagerReviewDate.ToString, myDigitalReviewDate.ToString, myRejectedDate.ToString, myInProgressDate.ToString, myDevelopedDate.ToString, myImplementedDate.ToString})
Dim mySQLTableColumns() As String = ({"ID", "myUser", "myDepartment", "mySubsidiary", "myTitle", "myRecurrence", "myImpact", "myTimeSaved", "myPriority", "myStatus", "myTechnology", "myDeveloper", "myCostSave", "myDescription", "myCommentary", "myDateSubmitted", "myDateModified", "myInReviewDate", "myManagerReviewDate", "myDigitalReviewDate", "myRejectedDate", "myInProgressDate", "myDevelopedDate", "myImplementedDate"})
SQL_InsertUpdate(SQLConnection, "INSERT INTO", "SIMSBase", mySQLTableColumns, myParameters)
This is the constructed command string output:
INSERT INTO SIMSBase (ID, myUser, myDepartment, mySubsidiary, myTitle,
myRecurrence, myImpact, myTimeSaved, myPriority, myStatus,
myTechnology, myDeveloper, myCostSave, myDescription, myCommentary,
myDateSubmitted, myDateModified, myInReviewDate, myManagerReviewDate,
myDigitalReviewDate, myRejectedDate, myInProgressDate,
myDevelopedDate, myImplementedDate) VALUES (#ID, #myUser,
#myDepartment, #mySubsidiary, #myTitle, #myRecurrence, #myImpact,
#myTimeSaved, #myPriority, #myStatus, #myTechnology, #myDeveloper,
#myCostSave, #myDescription, #myCommentary, #myDateSubmitted,
#myDateModified, #myInReviewDate, #myManagerReviewDate,
#myDigitalReviewDate, #myRejectedDate, #myInProgressDate,
#myDevelopedDate, #myImplementedDate)
This is the error I receive:
$exception {"Syntax error in INSERT INTO statement."} System.Data.OleDb.OleDbException
Now I have no clue what syntax error I could have, I looked here for another person who has no issue in this Stack question: Insert data into SQL database in VB.NET, my syntax is similar.
I don't know what is wrong, could it give out a syntax error if the Access database columns are not Data Type Short/Long Text?
The parameters are added properly (checked the debug).
Actually, I often find it too much work to create a complex insert routine. And even worse is I often don't care or want to supply all of the columns.
.net as a result has what is called a command builder for you.
And this quite much means you can write a lot of your code in a simular way to how VBA code in Access works.
So, say I want to add a new row - the table might have 50 columns, but I don't really care.
So, I can write the code this way:
Dim rstHotels As DataTable
rstHotels = MyRst("SELECT * FROM tblHotels WHERE ID = 0")
' now add 3 new hotels
For i = 1 To 3
Dim OneRow = rstHotels.NewRow
OneRow("HotelName") = "Hotel #" & i
OneRow("City") = "City #" & i
OneRow("FirstName") = "Test First name #" & i
OneRow("Active") = True
rstHotels.Rows.Add(OneRow)
Next
' ok, added rows to rstHotels - now write back to database
MyRstUpDate(rstHotels, "tblHotels")
' or update 5 rows and do compplex processing to exising data.
Dim rstFun As DataTable = MyRst("SELECT * from tblHotels where City = 'Banff'")
For Each MyRow As DataRow In rstFun.Rows
MyRow("Active") = True
' more complex cpde here
Next
' now send data changes back to database
MyRstUpdate(rstFun, "tblHotels")
So, note how we don't have to have some complex insert statement, and we don't hve to write some loop that gives one hoot about the number of columns. So the .net data operations have build in all this stuff for you - little or even next to no reason for you to try and re-invent the wheel here.
And the two handy dandy code routines I have? The are :
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New OleDbConnection(My.Settings.AccessDB)
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
rstData.TableName = strSQL
End Using
End Using
Return rstData
End Function
Public Sub MyRstUpdate(rstData As DataTable, strTableName As String)
Using conn As New OleDbConnection(My.Settings.AccessDB)
Using cmdSQL As New OleDbCommand("SELECT * from " & strTableName, conn)
Dim da As New OleDbDataAdapter(cmdSQL)
Dim daUP As New OleDbCommandBuilder(da)
conn.Open()
da.Update(rstData)
End Using
End Using
End Sub
Now, I am really rather free to just code out my general routines.
So, you need to say load up a grid, or even a combo box? You can now do this:
ListBox1.DataSource = MyRst("SELECT ID, Salutation from tblGender ORDER BY Salutation")
So, for a simple insert, or even edit of some rows? No need to create some monster huge insert statement with a boatload of parameters. Just create a data table, and then use a simple data row to either add new rows, or even update existing ones.
The beauty of above is not only do you eliminate a boatload of parameters, but you also get parameter safe, and even type conversions. So, you can for example do this:
OneRow("InvoiceDate") = Date.Today
Thus a strong typed value of "money" or integer, or datetime can be used in code - and no messey format convertions are required in most cases.
This so called "data base" first can be really handy, and often for some operations this is a lot less setup time and learning curve then say using EF, or even the previous dataset designer (EF = "Entity framework", which works really much like the older data set designer system - but introduction of these object model systems can be a big system to chew on when you just starting out).
But, no, don't write your own looping code to write out and create all the columns for a update command. (or insert command - note how that ONE routine can handle both updates or inserts. And you can even use row.Delete and then call tht update routine - it will also work!!.
If you think about this, that really amounts to a lot of work, and built in systems exist for this propose - saves you having to re-invent the wheel.
I'm dumb.
The order of the operations was off, this is what the function should have looked like:
Function SQL_InsertUpdate(mySQLConnection As OleDbConnection, mySQLCommand As String, mySQLTable As String, mySQLTableColumns() As String, myParameters() As String)
Dim myStringConstruct = mySQLCommand & " " & mySQLTable & " ("
'==============
For Each item In mySQLTableColumns
myStringConstruct = myStringConstruct & item & ", "
Next
myStringConstruct = Strings.Left(myStringConstruct, Len(myStringConstruct) - 2)
myStringConstruct = myStringConstruct & ") VALUES ("
For i As Integer = 0 To mySQLTableColumns.Length - 1
myStringConstruct = myStringConstruct & "#" & mySQLTableColumns(i) & ", "
Next
myStringConstruct = Strings.Left(myStringConstruct, Len(myStringConstruct) - 2)
myStringConstruct = myStringConstruct & ")"
Dim SQLCommand As OleDbCommand = New OleDbCommand(myStringConstruct, mySQLConnection)
For i As Integer = 0 To mySQLTableColumns.Length - 1
SQLCommand.Parameters.AddWithValue("#" & mySQLTableColumns(i), myParameters(i))
Next
SQLCommand.ExecuteNonQuery()
End Function
Basically, I was passing an incomplete command.

Logs file into a database

So, I have an application where I am able to drop a file into a button and the information will be shown on my database. To make things better I am trying after add something a query will run with an INNER JOIN where there are 2 tables, one of them will simply save the files info and the other one will save the date and time of that added file. I already have the LogsFile method:
Private Sub LogFileAdicionados()
Dim LogsFile As String = My.Application.Info.DirectoryPath
Dim logtext As String = lblName.Text
Dim logtext2 As String = lblSize.Text
Dim vt As String = "The file " & logtext & " com " & logtext2 & " KB " & "was added at " & TimeOfDay & " in " & Date.Today & "." & vbCrLf
My.Computer.FileSystem.WriteAllText(LogsFile + "\LogsAdded.txt", vt, True)
End Sub
So what should I do to INSERT the data and time values onto the Logs table?
As Zaggler pointed out, you need at least to attempt to do it yourself in order to post more meaningful question. However I'm going to set you on the track and see what happen...
First you need an approach on how to interact with your database. I'll show you how to do it with ADO.NET data objects, but keep in mind that there are other tools/frameworks to interact with a DB storage.
Next you need the connection string to your database. You can find hundreds of examples here.
Then you can do some fun stuff, like:
Using conn As New SqlConnection("connection string to your DB goes here")
Using cmd = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Logs (fields definition) VALUES" + vt
cmd.ExecuteNonQuery()
End Using
End Using
Basically this outlining saving data to a SQL DB, using ADO.NET data objects.

Possible to query As400 DB2 via VB.Net without a PRG?

After spending a few days researching and trying to figure this out solo, I could really use some help.
I'm trying to query the As400's database directly from .Net without the use of a As400 program file. I have very little support other than "go ahead and try" from the As400 administrators (I'm being told what I'm attempting hasn't been done here before).
I'd really like to use CWBX. The code below successfully connects, but I could really use a pointer in the right direction on how to build a query:
Dim As400 As New AS400System
Dim AsProgram As New cwbx.Program
Dim AsCommand As New cwbx.Command
Dim strQuery As String
As400.Define("AS400")
As400.UserID = ""
As400.Password = ""
As400.IPAddress = ""
As400.Connect(cwbcoServiceEnum.cwbcoServiceRemoteCmd)
If As400.IsConnected(cwbcoServiceEnum.cwbcoServiceRemoteCmd) = 1 Then
MsgBox("Valid Connection")
Else
MsgBox("Invalid Connection")
Exit Sub
End If
'-----------------------------------------------------------------------------------------
'Trying to figure out first if this syntax is correct, and if so... where/how to call it??
'-----------------------------------------------------------------------------------------
strQuery = "SELECT * FROM Library.File WHERE FILEFIELD='Criteria'"
' ---
AsProgram.LibraryName = ""
AsProgram.ProgramName = "" '?
AsProgram.system = As400
'Assuming this will end up being a program call?
'AsProgram.Call()
As400.Disconnect(cwbcoServiceEnum.cwbcoServiceRemoteCmd)
I'm very open to any other methods/suggestions. I've looked for guides from IBM's site as well as MSDN and neither actually do direct querying without the use of an As400 program file. Is this even possible?
Here is a simple console app that will retrieve all the records from one table and display the row count.
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim cmd As New OleDbCommand
Dim table As String = "YOUR TABLE"
cmd.CommandText = "SELECT * FROM " & table
Dim ip As String = "YOUR AS/400 IP GOES HERE"
Dim user As String = "YOUR USER ID"
Dim pass As String = "YOUR PASSWORD"
Dim defaultLib As String = "YOUR LIBRARY"
Dim connstring As String = "Provider=IBMDA400;" & _
"Data Source=" & ip & ";" & _
"Force Translate=0;" & _
"Default Collection=" & defaultLib & ";" & _
"User ID=" & user & ";" & _
"Password=" & pass
cmd.Connection = New OleDbConnection(connstring)
cmd.Connection.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Console.WriteLine(dt.Rows.Count)
Console.WriteLine("Press ENTER to close...")
Console.ReadLine()
End Sub
End Module
The remotecmd service is basically a Rexcd daemon. Not sure why you're messing with that when you want to simple query a DB table. The integrated DB in IBM i is accessible via ODBC, OLEDB, JBDC and most importantly for you a ADO.NET provider.
http://www-03.ibm.com/systems/power/software/i/access/windows/dotnet.html
All of the above mentioned drivers are available in the IBM i Access software. Note that while some of the IBM i Access features are chargeable, ex 5250 emulation, and you must have bought a license; the data access providers are not.
Included in the IBM i Access package is a collection of documentation known as the "Programmers Toolkit"
An example using the .NET data provider from that toolkit:
Public Sub Example()
Dim cn As iDB2Connection = New iDB2Connection("DataSource=mySystemi;")
Dim da As New iDB2DataAdapter("select * from mylib.mytable", cn)
End Sub
Lastly note that the (free) .NET provider doesn't support Microsoft's Entity Framework (EF). If you need EF support, you'll have to pay for DB2 Connect
http://www-03.ibm.com/software/products/en/db2-connect-family

VB.NET Linq to SQL - Query from table

I am starting with Linq to SQL in VB.NET, and trying to figure out how to make a simple query to a database.
I want to do it all programaticly.
I have made a connection to the database with a connectionstring, and this works fine - I can get a message if the database exists or not.
But when I want to query a table, I am missing the part where I connest to the table. I have googled a lot to find an answer for thi, but
no luck. Can anyone point me in the right direction?
Code:
Dim strContactString, strDBServer, strDBName, strSQLUser, strSQLPW As String
strDBServer = "MyServer"
strDBName = "Northwind"
strSQLUser = "sa"
strSQLPW = "MyPW"
strContactString = ""
strContactString = strContactString & "data source=" & strDBServer & ";"
strContactString = strContactString & "initial catalog=" & strDBName & ";"
strContactString = strContactString & "user id=" & strSQLUser & ";"
strContactString = strContactString & "password=" & strSQLPW & ";"
Dim MyContext As New DataContext(strContactString)
'This works:
If MyContext.DatabaseExists Then
MsgBox("DB Exists")
Else
MsgBox("DB Does Not Exist")
End If
'This is the query I want to run (copied from samples I found)
Dim TEST = From c In MyContext.Customers _
Select c.ContactName
Error message:
'Customers' is not a member of 'System.Data.Linq.DataContext'.
First off you're not supposed to use DataContext directly.
You add a new dbml file to your project and map that to the database using the editor (this means connecting visual studio to your database, then dragging the tables you want from the server explorer to the dbml editor).
That will generate for you a class colled something like NortwindDataContext (you can control this from the properties pane in the editor).
You can then use that to write your queries:
Dim context As New DataContext(strContactString)
Dim TEST = From c In context.Customers _
Select c.ContactName
http://msdn.microsoft.com/en-us/library/bb399375.aspx
"Best practice is to declare a strongly typed DataContext instead of relying on the basic DataContext class and the GetTable method. A strongly typed DataContext declares all Table collections as members of the context, as in the following example."
As long as the db is connected correctly, this may be your problem.

ASP.NET error: Error 1 'isEqual' is not declared. It may be inaccessible due to its protection level

Hope there's .NET developers here that could enlighten me up.
I actually already made up some pages in .NET environment,
and i'm using VB.NET as my back-end.
Phewww....!
I have 2 files of A.ascx and B.ascx
and each of them have the A.ascx.vb and B.ascx.vb files altogether.
But here's the interesting part.
I use 'isEqual' variable inside one of the method I typed in.
And if I use it inside one of the vb file then, I could not use it into another vb file.
Thus, Once I used that 'isEqual' inside of these 2 vb (files), I will got the error appeared as from one of the vb file;
'isEqual' is not declared. It may be inaccessible due to its protection level.
Is there any alternative way out for this?
My code is actually this one;
Protected Sub bindTable()
'add somemore for searching with dropdown list
Dim sSql As String = "SELECT *, C.companyname FROM quotationmst Q"
Dim sColumn As String = Nothing
Dim sSearchField As String = Nothing
Dim sOptional As String = Nothing
If txtQuotationSearchField.Text.Length > 0 Then
sColumn = drpQuotationSearchField.SelectedItem.Value
sSearchField = " WHERE " & sColumn & " LIKE '%" & txtQuotationSearchField.Text & "%' "
sSql &= sSearchField
If isEqual(sColumn, "companyname") = 0 Or isEqual(sColumn, "customername") = 0 Then
sSearchField = " INNER JOIN customermst C on Q.customerid = C.customerid WHERE C." & sColumn & " LIKE '%" & txtQuotationSearchField.Text & "%'"
sSql &= sSearchField
End If
Else
sSearchField = " INNER JOIN customermst C ON Q.customerid = C.customerid"
sSql &= sSearchField
End If
Dim oCommon As New Common
sSql &= " ORDER BY quotationcode"
Dim dT As DataTable = oCommon.getDataSet(sSql)
dgRecord.DataSource = dT
dgRecord.DataBind()
lblTotal.Text = dT.Rows.Count
End Sub
Just do
If sColumn.Equals("companyname") Or sColumn.Equals("customername") Then
What I think is happening here is this:
When you create a file in Visual Studio (vb.net) and add a control using the designer it creates a file called "filename.aspx.designer.vb" You may have created the first page using the designer, and copied it to create the second page, losing the design file in that process.
This would give you the above error as the design file has auto generated field declarations in it, that look like this:
Protected WithEvents rptPackages As Global.System.Web.UI.WebControls.Repeater
In any case, try using the above declration for your vars, or at least make them "Protected" or "Public" so there is some kind of scope to them. Using dim can cause all kinds of runtime and compilation errors which are hard to diagnose because of type inferance.