To register for an Internet.com membership to receive newsletters and white papers, use the Register button ABOVE.
To participate in the message forums BELOW, click here
VBForums  

VB Wire News
Sell Your Code and Make Money?
Creating your own Tetris game using VB.NET
Article :: Improving Software Economics, Part 4 of 7: Top 10 Principles of Iterative Software Management
Building Composable Apps in .NET 4 with the Managed Extensibility Framework
CLR Inside Out: Formatting and Parsing Time Intervals in the .NET Framework 4



Go Back   VBForums > VBForums CodeBank > CodeBank - Visual Basic .NET

Reply Post New Thread
 
Thread Tools Search this Thread Display Modes
Old May 20th, 2007, 09:45 PM   #1
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Retrieving and Saving Data in Databases

C# version here.

There is all sorts of literature on this topic but people still keep asking the same questions. I'm creating this thread so I can send people here to look at some example code that I know will demonstrate all the principles they need. These principles can be extended or adjusted and applied to any data access situation. This code uses members of the System.Data.SqlClient namespace. If you're not using SQL Server then it's a simple matter of switching to the corresponding types of the appropriate namespace for your data source. For example, if you're using an Access database then you'd use an OleDb.OleDbConnection rather than an SqlClient.SqlConnection.

Retrieving a single value. The ExecuteScalar method returns the value from the first column of the first row of the query's result set:
vb.net Code:
  1. Using connection As New SqlConnection("connection string here")
  2.     Using command As New SqlCommand("SELECT SUM(Quantity) FROM StockItem", _
  3.                                     connection)
  4.         connection.Open()
  5.  
  6.         Dim totalQuantity As Double = CDbl(command.ExecuteScalar())
  7.  
  8.         'Use totalQuantity here.
  9.     End Using
  10. End Using
Retrieving multiple records that will be read and discarded. The ExecuteReader method provides read-only, forward-only access to the entire result set:
vb.net Code:
  1. Using connection As New SqlConnection("connection string here")
  2.     Using command As New SqlCommand("SELECT Quantity, Unit, Name FROM StockItem", _
  3.                                     connection)
  4.         connection.Open()
  5.  
  6.         Using reader As SqlDataReader = command.ExecuteReader()
  7.             While reader.Read()
  8.                 MessageBox.Show(String.Format("There are {0} {1} of {2} remaining in stock.", _
  9.                                               reader("Quantity"), _
  10.                                               reader("Unit"), _
  11.                                               reader("Name")))
  12.             End While
  13.         End Using
  14.     End Using
  15. End Using
Retrieving multiple records for display that will not be updated. The DataTable.Load method will populate a DataTable with the result set exposed by a DataReader:
vb.net Code:
  1. Using connection As New SqlConnection("connection string here")
  2.     Using command As New SqlCommand("SELECT Quantity, Unit, Name FROM StockItem", _
  3.                                     connection)
  4.         connection.Open()
  5.  
  6.         Using reader As SqlDataReader = command.ExecuteReader()
  7.             Dim table As New DataTable
  8.  
  9.             table.Load(reader)
  10.  
  11.             'The table can be used here to display the data.
  12.             'That will most likely be done via data-binding but that is NOT a data access issue.
  13.         End Using
  14.     End Using
  15. End Using
Note that DataTable.Load is new in .NET 2.0. I have provided code here to populate a DataTable from a DataReader in .NET 1.x

Retrieving multiple records for display and editing, then saving the changes. The DataAdapter.Fill method populates a DataTable with the contents of the result set of a query. The DataAdapter.Update method saves the changes in a DataTable in accordance with the SQL statements contained in the DeleteCommand, InsertCommand and UpdateCommand properties:
vb.net Code:
  1. Private connection As New SqlConnection("connection string here")
  2. Private adapter As New SqlDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem", _
  3.                                       connection)
  4. Private table As New DataTable
  5.  
  6. Private Sub InitialiseDataAdapter()
  7.     Dim delete As New SqlCommand("DELETE FROM StockItem WHERE ID = @ID", Me.connection)
  8.     Dim insert As New SqlCommand("INSERT INTO StockItem (Name, Quantity, Unit) VALUES (@Name, @Quantity, @Unit)", Me.connection)
  9.     Dim update As New SqlCommand("UPDATE StockItem SET Name = @Name, Quantity = @Quantity, Unit = @Unit WHERE ID = @ID", Me.connection)
  10.  
  11.     delete.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")
  12.  
  13.     insert.Parameters.Add("@Name", SqlDbType.VarChar, 100, "Name")
  14.     insert.Parameters.Add("@Quantity", SqlDbType.Float, 8, "Quantity")
  15.     insert.Parameters.Add("@Unit", SqlDbType.VarChar, 10, "Unit")
  16.  
  17.     update.Parameters.Add("@Name", SqlDbType.VarChar, 100, "Name")
  18.     update.Parameters.Add("@Quantity", SqlDbType.Float, 8, "Quantity")
  19.     update.Parameters.Add("@Unit", SqlDbType.VarChar, 10, "Unit")
  20.     update.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")
  21.  
  22.     Me.adapter.DeleteCommand = delete
  23.     Me.adapter.InsertCommand = insert
  24.     Me.adapter.UpdateCommand = update
  25.  
  26.     Me.adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
  27. End Sub
  28.  
  29. Private Sub GetData()
  30.     'Retrieve the data.
  31.     Me.adapter.Fill(Me.table)
  32.  
  33.     'The table can be used here to display and edit the data.
  34.     'That will most likely involve data-binding but that is not a data access issue.
  35. End Sub
  36.  
  37. Private Sub SaveData()
  38.     'Save the changes.
  39.     Me.adapter.Update(Me.table)
  40. End Sub
Note that if your query involves only one table and it has a primary key then you can take the easy option and use a CommandBuilder instead of creating the non-query commands yourself:
vb.net Code:
  1. Private connection As New SqlConnection("connection string here")
  2. Private adapter As New SqlDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem", _
  3.                                       connection)
  4. Private builder As New SqlCommandBuilder(adapter)
  5. Private table As New DataTable
  6.  
  7. Private Sub InitialiseDataAdapter()
  8.     Me.adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
  9. End Sub
  10.  
  11. Private Sub GetData()
  12.     'Retrieve the data.
  13.     Me.adapter.Fill(Me.table)
  14.  
  15.     'The table can be used here to display and edit the data.
  16.     'That will most likely involve data-binding but that is not a data access issue.
  17. End Sub
  18.  
  19. Private Sub SaveData()
  20.     'Save the changes.
  21.     Me.adapter.Update(Me.table)
  22. End Sub
Saving changes directly to one or more records in the database. The Command.ExecuteNonQuery method will execute any SQL statement and not return a result set. It can be used to execute a query but you'd never use it for that unless you were populating a view or temp table. Usually you'd use ExecuteNonQuery to execute a DELETE, INSERT or UPDATE command:
vb.net Code:
  1. Using connection As New SqlConnection("connection string here")
  2.     Using command As New SqlCommand("INSERT INTO StockItem (Name, Quantity, Unit) VALUES (@Name, @Quantity, @Unit)", _
  3.                                     connection)
  4.         command.Parameters.AddWithValue("@Name", someName)
  5.         command.Parameters.AddWithValue("@Quantity", someQuantity)
  6.         command.Parameters.AddWithValue("@Unit", someUnit)
  7.  
  8.         connection.Open()
  9.  
  10.         command.ExecuteNonQuery()
  11.     End Using
  12. End Using
Note that I have not provided code for disposing objects or catching exceptions. Those are general topics that do not relate specifically to data access so they should be learned elsewhere.

Note also the DataAdapter.Fill, DataAdapter.Update and Command.ExecuteNonQuery methods are all functions. All three return an Integer that contains the number of records that were either retrieved (Fill) or saved (Update, ExecuteNonQuery).

Finally, this code uses all the "old style" data access types. In .NET 2.0 I suggest creating a Data Source to generate a typed DataSet and TableAdapters. The principles there are basically the same except that you have to write less code. All SQL statements are added via the DataSet designer and all you really have to do is create TableAdapters and call their methods. Even the connections are hidden within the TableAdapters so it's all much easier. Understanding what's above should help you understand how TableAdapters work internally though.

EDIT: Note that I have updated the code examples slightly in this post and post #3 to more accurately reflect real usage situations, particularly using a DataAdapter to get and save data in separate methods rather than in the same method.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET

Last edited by jmcilhinney; Nov 8th, 2008 at 07:30 PM.
jmcilhinney is online now   Reply With Quote
Old Jun 7th, 2007, 01:09 AM   #2
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

To find the appropriate connection string for your ADO.NET provider visit www.connectionstrings.com.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Jan 17th, 2008, 09:47 PM   #3
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Inserting multiple records into a table. This situation is much like the fourth example above, except you don't need to retrieve any data to start with and you obviously don't need the UpdateCommand and DeleteCommand:
vb.net Code:
  1. Using connection As New SqlConnection("connection string here")
  2.     Using adapter As New SqlDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem", _
  3.                                         connection)
  4.         Dim insert As New SqlCommand("INSERT INTO StockItem (Name, Quantity, Unit) VALUES (@Name, @Quantity, @Unit)", _
  5.                                      connection)
  6.         insert.Parameters.Add("@Name", SqlDbType.VarChar, 100, "Name")
  7.         insert.Parameters.Add("@Quantity", SqlDbType.Float, 8, "Quantity")
  8.         insert.Parameters.Add("@Unit", SqlDbType.VarChar, 10, "Unit")
  9.         adapter.InsertCommand = insert
  10.         adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
  11.         Dim table As New DataTable
  12.         'Retrieve the data.
  13.         adapter.FillSchema(table, SchemaType.Source)
  14.         'Add the new rows to the DataTable, e.g.
  15.         Dim row As DataRow = table.NewRow()
  16.         row("Name") = someName
  17.         row("Quantity") = someQuantity
  18.         row("Unit") = someUnit
  19.         table.Rows.Add(row)
  20.         'Save the changes.
  21.         adapter.Update(table)
  22.     End Using
  23. End Using
I should also point out that you don't actually need the SelectCommand and the FillSchema call either. You can simply build the DataTable schema yourself if you like.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET

Last edited by jmcilhinney; Apr 22nd, 2009 at 02:57 AM.
jmcilhinney is online now   Reply With Quote
Old Jan 22nd, 2008, 09:12 AM   #4
bishnoi
New Member
 
Join Date: Jan 08
Posts: 2
bishnoi is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

hi jmcilhinney,
Its a nice documentation.
(This is my first post.)
Still i would request a good class/module for db connection in access.
Particularly i need to access ms access though local network.what would be the best class code.
I appreciate your view.
I think you will help me and people like me. I m trying to work in .net.i have done little programmings in vb6 and .net 05. i have been on this site for last 4-6 hrs. got excellent helping examples and links.
Thanks again.
bishnoi is offline   Reply With Quote
Old Jan 22nd, 2008, 06:06 PM   #5
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by bishnoi
hi jmcilhinney,
Its a nice documentation.
(This is my first post.)
Still i would request a good class/module for db connection in access.
Particularly i need to access ms access though local network.what would be the best class code.
I appreciate your view.
I think you will help me and people like me. I m trying to work in .net.i have done little programmings in vb6 and .net 05. i have been on this site for last 4-6 hrs. got excellent helping examples and links.
Thanks again.
The code is basically no different for Access. As I said in my first post:
Quote:
For example, if you're using an Access database then you'd use an OleDb.OleDbConnection rather than an SqlClient.SqlConnection.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Jun 12th, 2008, 04:02 AM   #6
bizzy_e23
Lively Member
 
Join Date: Jun 08
Location: Philippines
Posts: 69
bizzy_e23 is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

Hi, I found your compilation verry usefull in my project... Thank you... Since I'm a new user of VB Express Edition 2008, can you help me in my problem regarding retrieving a recordset and afterwards editing one of its field.

Additional Info:

in the first scenario, im going to create a new data, and because this is a Time keeping System, First Im just going to get the Time IN and leave the TimeOUT Column blank.. what i want to do is i want to retrive this recordset and update the TimeOUT column. Thanks.

Table: TIME_IN_OUT

EmpNo TimeIN TimeOUT

00001 8:30 AM N/A
bizzy_e23 is offline   Reply With Quote
Old Jun 12th, 2008, 06:46 AM   #7
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by bizzy_e23
Hi, I found your compilation verry usefull in my project... Thank you... Since I'm a new user of VB Express Edition 2008, can you help me in my problem regarding retrieving a recordset and afterwards editing one of its field.

Additional Info:

in the first scenario, im going to create a new data, and because this is a Time keeping System, First Im just going to get the Time IN and leave the TimeOUT Column blank.. what i want to do is i want to retrive this recordset and update the TimeOUT column. Thanks.

Table: TIME_IN_OUT

EmpNo TimeIN TimeOUT

00001 8:30 AM N/A
This thread already shows you how to retrieve the data from the database and save it back again. Editing the data in between is beyond the scope of this thread. Start your own thread in the VB.NET forum.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Oct 22nd, 2008, 11:45 PM   #8
venuspcs
New Member
 
Join Date: Oct 08
Posts: 13
venuspcs is an unknown quantity at this point (<10)
Angry Re: Retrieving and Saving Data in Databases

Okay I am using the code below:

Code:
        Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Richard Colbert\Documents\Visual Studio 2008\Projects\WindowsApplication1\WindowsApplication1\shenandoah.accdb'")
        Dim adapter As New OleDb.OleDbDataAdapter("SELECT ID, Date, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances FROM Shenandoahs", connection)
        Dim insert As New OleDb.OleDbCommand("INSERT INTO Shenandoahs (Date, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances) VALUES (@Date, @Driver, @Truck, @Customer, @Rate, @Where_From, @Where_To, @Pit_Ticket, @PO_Number, @Yards_Tons, @Description, @QP_Fee, @Fuel, @Expenses, @Advances)", connection)

        insert.Parameters.Add("@Date", OleDb.OleDbType.VarChar, 20, "mmddyy")
        insert.Parameters.Add("@Driver", OleDb.OleDbType.VarChar, 20, "Driver")
        insert.Parameters.Add("@Truck", OleDb.OleDbType.VarChar, 10, "Truck")
        insert.Parameters.Add("@Customer", OleDb.OleDbType.VarChar, 10, "Customer")
        insert.Parameters.Add("@Rate", OleDb.OleDbType.VarChar, 10, "Rate")
        insert.Parameters.Add("@Where_From", OleDb.OleDbType.VarChar, 100, "Where_From")
        insert.Parameters.Add("@Where_To", OleDb.OleDbType.VarChar, 100, "Where_To")
        insert.Parameters.Add("@Pit_Ticket", OleDb.OleDbType.VarChar, 20, "Pit_Ticket")
        insert.Parameters.Add("@PO_Number", OleDb.OleDbType.VarChar, 20, "PO_Number")
        insert.Parameters.Add("@Yards_Tons", OleDb.OleDbType.VarChar, 20, "Yards_Tons")
        insert.Parameters.Add("@Description", OleDb.OleDbType.VarChar, 100, "Description")
        insert.Parameters.Add("@QP_Fee", OleDb.OleDbType.VarChar, 20, "QP_Fee")
        insert.Parameters.Add("@Fuel", OleDb.OleDbType.VarChar, 20, "Fuel")
        insert.Parameters.Add("@Expenses", OleDb.OleDbType.VarChar, 20, "Expenses")
        insert.Parameters.Add("@Advances", OleDb.OleDbType.VarChar, 20, "Advances")

        adapter.InsertCommand = insert
            adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

        Dim table As New DataTable

        'Retrieve the data.
            adapter.FillSchema(table, SchemaType.Source)

            'Add the new rows to the DataTable, e.g.
            Dim row As DataRow = table.NewRow()

        row("Date") = mmddyy
            row("Driver") = Driver
            row("Truck") = Truck
            row("Customer") = Customer
            row("Rate") = Rate
            row("Where_From") = Where_From
            row("Where_To") = Where_To
            row("Pit_Ticket") = Pit_Ticket
            row("PO_Number") = Po_Number
            row("Yards_Tons") = Yards_Tons
            row("Description") = Description
            row("QP_Fee") = QP_Fee
            row("Fuel") = Fuel
            row("Expenses") = Expenses
            row("Advances") = Advances

            table.Rows.Add(row)

        'Save the changes.
        adapter.Update(table)
I show no errors in VS.net but when I run the debug and click on the Submit button I get the following error:

Syntax error in INSERT INTO statement.

I have been trying to get this to work for like HOURS. Please help!
venuspcs is offline   Reply With Quote
Old Oct 23rd, 2008, 06:25 AM   #9
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by venuspcs
Okay I am using the code below:

Code:
        Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Richard Colbert\Documents\Visual Studio 2008\Projects\WindowsApplication1\WindowsApplication1\shenandoah.accdb'")
        Dim adapter As New OleDb.OleDbDataAdapter("SELECT ID, Date, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances FROM Shenandoahs", connection)
        Dim insert As New OleDb.OleDbCommand("INSERT INTO Shenandoahs (Date, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances) VALUES (@Date, @Driver, @Truck, @Customer, @Rate, @Where_From, @Where_To, @Pit_Ticket, @PO_Number, @Yards_Tons, @Description, @QP_Fee, @Fuel, @Expenses, @Advances)", connection)

        insert.Parameters.Add("@Date", OleDb.OleDbType.VarChar, 20, "mmddyy")
        insert.Parameters.Add("@Driver", OleDb.OleDbType.VarChar, 20, "Driver")
        insert.Parameters.Add("@Truck", OleDb.OleDbType.VarChar, 10, "Truck")
        insert.Parameters.Add("@Customer", OleDb.OleDbType.VarChar, 10, "Customer")
        insert.Parameters.Add("@Rate", OleDb.OleDbType.VarChar, 10, "Rate")
        insert.Parameters.Add("@Where_From", OleDb.OleDbType.VarChar, 100, "Where_From")
        insert.Parameters.Add("@Where_To", OleDb.OleDbType.VarChar, 100, "Where_To")
        insert.Parameters.Add("@Pit_Ticket", OleDb.OleDbType.VarChar, 20, "Pit_Ticket")
        insert.Parameters.Add("@PO_Number", OleDb.OleDbType.VarChar, 20, "PO_Number")
        insert.Parameters.Add("@Yards_Tons", OleDb.OleDbType.VarChar, 20, "Yards_Tons")
        insert.Parameters.Add("@Description", OleDb.OleDbType.VarChar, 100, "Description")
        insert.Parameters.Add("@QP_Fee", OleDb.OleDbType.VarChar, 20, "QP_Fee")
        insert.Parameters.Add("@Fuel", OleDb.OleDbType.VarChar, 20, "Fuel")
        insert.Parameters.Add("@Expenses", OleDb.OleDbType.VarChar, 20, "Expenses")
        insert.Parameters.Add("@Advances", OleDb.OleDbType.VarChar, 20, "Advances")

        adapter.InsertCommand = insert
            adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

        Dim table As New DataTable

        'Retrieve the data.
            adapter.FillSchema(table, SchemaType.Source)

            'Add the new rows to the DataTable, e.g.
            Dim row As DataRow = table.NewRow()

        row("Date") = mmddyy
            row("Driver") = Driver
            row("Truck") = Truck
            row("Customer") = Customer
            row("Rate") = Rate
            row("Where_From") = Where_From
            row("Where_To") = Where_To
            row("Pit_Ticket") = Pit_Ticket
            row("PO_Number") = Po_Number
            row("Yards_Tons") = Yards_Tons
            row("Description") = Description
            row("QP_Fee") = QP_Fee
            row("Fuel") = Fuel
            row("Expenses") = Expenses
            row("Advances") = Advances

            table.Rows.Add(row)

        'Save the changes.
        adapter.Update(table)
I show no errors in VS.net but when I run the debug and click on the Submit button I get the following error:

Syntax error in INSERT INTO statement.

I have been trying to get this to work for like HOURS. Please help!
When you get a syntax error in what seems to be valid SQL code it's often because one of your column names is a reserved word. In your case the most likely culprit is Date. Wrap the identifier in brackets, i.e. [Date], to force it to be interpreted correctly.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Oct 23rd, 2008, 09:32 AM   #10
venuspcs
New Member
 
Join Date: Oct 08
Posts: 13
venuspcs is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

Okay you where so write about the date....I renamed all my fields in the database and in my code to mmddyy and it started working, well sort of....it is writing to the database now but it is not filling the database with the information from the form, instead all my fields say either: "System.Windows.Forms", "System.Win", or "System.Windows.Forms.TextBox,Text:"

WTH - Here is the complete revised code:

Code:
    Private Sub Submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit.Click

        Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Richard Colbert\Documents\Visual Studio 2008\Projects\WindowsApplication1\WindowsApplication1\shenandoah.accdb'")
        Dim adapter As New OleDb.OleDbDataAdapter("SELECT ID, mmddyy, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances FROM Shenandoahs", connection)
        Dim insert As New OleDb.OleDbCommand("INSERT INTO Shenandoahs (mmddyy, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances) VALUES (@mmddyy, @Driver, @Truck, @Customer, @Rate, @Where_From, @Where_To, @Pit_Ticket, @PO_Number, @Yards_Tons, @Description, @QP_Fee, @Fuel, @Expenses, @Advances)", connection)

        insert.Parameters.Add("@mmddyy", OleDb.OleDbType.VarChar, 20, "mmddyy")
        insert.Parameters.Add("@Driver", OleDb.OleDbType.VarChar, 20, "Driver")
        insert.Parameters.Add("@Truck", OleDb.OleDbType.VarChar, 10, "Truck")
        insert.Parameters.Add("@Customer", OleDb.OleDbType.VarChar, 10, "Customer")
        insert.Parameters.Add("@Rate", OleDb.OleDbType.VarChar, 10, "Rate")
        insert.Parameters.Add("@Where_From", OleDb.OleDbType.VarChar, 100, "Where_From")
        insert.Parameters.Add("@Where_To", OleDb.OleDbType.VarChar, 100, "Where_To")
        insert.Parameters.Add("@Pit_Ticket", OleDb.OleDbType.VarChar, 20, "Pit_Ticket")
        insert.Parameters.Add("@PO_Number", OleDb.OleDbType.VarChar, 20, "PO_Number")
        insert.Parameters.Add("@Yards_Tons", OleDb.OleDbType.VarChar, 20, "Yards_Tons")
        insert.Parameters.Add("@Description", OleDb.OleDbType.VarChar, 100, "Description")
        insert.Parameters.Add("@QP_Fee", OleDb.OleDbType.VarChar, 20, "QP_Fee")
        insert.Parameters.Add("@Fuel", OleDb.OleDbType.VarChar, 20, "Fuel")
        insert.Parameters.Add("@Expenses", OleDb.OleDbType.VarChar, 20, "Expenses")
        insert.Parameters.Add("@Advances", OleDb.OleDbType.VarChar, 20, "Advances")

        adapter.InsertCommand = insert
        adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

        Dim table As New DataTable

        'Retrieve the data.
        adapter.FillSchema(table, SchemaType.Source)

        'Add the new rows to the DataTable, e.g.
        Dim row As DataRow = table.NewRow()

        row("mmddyy") = mmddyy
        row("Driver") = Driver
        row("Truck") = Truck
        row("Customer") = Customer
        row("Rate") = Rate
        row("Where_From") = Where_From
        row("Where_To") = Where_To
        row("Pit_Ticket") = Pit_Ticket
        row("PO_Number") = Po_Number
        row("Yards_Tons") = Yards_Tons
        row("Description") = Description
        row("QP_Fee") = QP_Fee
        row("Fuel") = Fuel
        row("Expenses") = Expenses
        row("Advances") = Advances

        table.Rows.Add(row)

        'Save the changes.
        adapter.Update(table)

    End Sub
venuspcs is offline   Reply With Quote
Old Oct 23rd, 2008, 09:38 AM   #11
MaslowB
Addicted Member
 
Join Date: Sep 08
Location: Jacksonville, Florida
Posts: 147
MaslowB is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

row("mmddyy") = mmddyy
row("Driver") = Driver

So mmddyy in this instance would be a text box? you need to do this instead if that's the case:

row("mmddyy")=mmddyy.text
MaslowB is offline   Reply With Quote
Old Oct 23rd, 2008, 11:28 AM   #12
venuspcs
New Member
 
Join Date: Oct 08
Posts: 13
venuspcs is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

Thanks so much MaslowB and jmcilhinney that code is working now.

Now I have another question....I need it to select which table to write to based on the user selection in the "Company" field on my form. There are three divisions to this company and thus three different databases. Those divisions are: "Shenandoah", "Shenandoahs_Covered_Wagon" and "Shenandoahs_Heavy_Haul" each with tables in the db named the same. All fields submitted to the tables are the same, it just needs to know which table to submit (input) to.
venuspcs is offline   Reply With Quote
Old Oct 23rd, 2008, 12:27 PM   #13
MaslowB
Addicted Member
 
Join Date: Sep 08
Location: Jacksonville, Florida
Posts: 147
MaslowB is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

Dim insert As New OleDb.OleDbCommand("INSERT INTO "+company.text+"(mmddyy, Driver, Truck, Customer, Rate, Where_From, Where_To, Pit_Ticket, PO_Number, Yards_Tons, Description, QP_Fee, Fuel, Expenses, Advances) VALUES (@mmddyy, @Driver, @Truck, @Customer, @Rate, @Where_From, @Where_To, @Pit_Ticket, @PO_Number, @Yards_Tons, @Description, @QP_Fee, @Fuel, @Expenses, @Advances)", connection)

How about that?
MaslowB is offline   Reply With Quote
Old Oct 23rd, 2008, 02:18 PM   #14
venuspcs
New Member
 
Join Date: Oct 08
Posts: 13
venuspcs is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

That would probably work a lot easier and shorten my code a tad, but I figured it out using this:

If Company.Text = "Shenandoah" Then

original code here

ElseIf Company.Text = "Shenandoahs_Covered_Wagon" Then

revised code here

ElseIf Company.Text = "Shenandoahs_Heavy_Haul" Then

more revised code here

End If

Not nearly as pretty or as short but it worked flawlessly. I will remember your suggestion and when I go through and revise (shorten my code) I will implement it.
venuspcs is offline   Reply With Quote
Old Oct 23rd, 2008, 02:24 PM   #15
MaslowB
Addicted Member
 
Join Date: Sep 08
Location: Jacksonville, Florida
Posts: 147
MaslowB is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

mark your thread resolved, rate those users that helped =)
MaslowB is offline   Reply With Quote
Old Oct 23rd, 2008, 02:36 PM   #16
venuspcs
New Member
 
Join Date: Oct 08
Posts: 13
venuspcs is an unknown quantity at this point (<10)
Thumbs up Re: Retrieving and Saving Data in Databases

Okay I rated both of you who helped me going to mark my original thread on this issue resolved....I have posted a new thread with a new issue if you guys can help again it would be greatly appreciated. Thanks!
venuspcs is offline   Reply With Quote
Old Nov 8th, 2008, 07:27 PM   #17
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Note that I have updated the code examples slightly in posts #1 and #3 to more accurately reflect real usage situations, particularly using a DataAdapter to get and save data in separate methods rather than in the same method.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Nov 14th, 2008, 07:06 AM   #18
cuterita7
Junior Member
 
Join Date: Sep 08
Posts: 21
cuterita7 is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

vb Code:
  1. Using connection As New SqlConnection("connection string here")
  2. Using command As New SqlCommand("SELECT SUM(Quantity) FROM StockItem",
  3. _connection) 
  4. connection.Open()
  5. Dim totalQuantity As Double = CDbl(command.ExecuteScalar()) 
  6. 'Use totalQuantity here.
  7. End Using

Why in this code snippet you don't close the connection?and how do you handle a exception(database exception)?

thanks
cuterita7 is offline   Reply With Quote
Old Nov 14th, 2008, 05:42 PM   #19
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by cuterita7
vb Code:
  1. Using connection As New SqlConnection("connection string here")
  2. Using command As New SqlCommand("SELECT SUM(Quantity) FROM StockItem",
  3. _connection) 
  4. connection.Open()
  5. Dim totalQuantity As Double = CDbl(command.ExecuteScalar()) 
  6. 'Use totalQuantity here.
  7. End Using

Why in this code snippet you don't close the connection?and how do you handle a exception(database exception)?

thanks
I don't close the connection explicitly because it gets disposed at the End Using line, which implicitly closes it. I have recently changed the code to make use of a Using block. My original code did close the connection explicitly.

As I said in my first post, I haven't included any exception handling because that's a separate topic that isn't related to data access specifically. In a real situation, yes, you would provide appropriate exception handling. For this example I didn't want to draw attention away from the actual topic of the thread, which is the data access itself. In a real situation you might put the exception handler inside the Using block(s) or outside, depending on the circumstances and your preference. One of the reasons you should use Using blocks is that they ensure that an object is disposed even if an exception is thrown, so you don't have to do anything extra to dispose the data access objects.
vb.net Code:
  1. Try
  2.     Using connection As New SqlConnection("connection string here")
  3.         Using command As New SqlCommand("SELECT SUM(Quantity) FROM StockItem", _
  4.                                         connection)
  5.             connection.Open()
  6.             Dim totalQuantity As Double = CDbl(command.ExecuteScalar())
  7.             'Use totalQuantity here.
  8.         End Using
  9.     End Using
  10. Catch ex As SqlException
  11.     For Each er As SqlError In ex.Errors
  12.         MessageBox.Show(er.Message)
  13.     Next
  14. End Try
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Oct 31st, 2009, 11:34 AM   #20
LuxCoder
Hyperactive Member
 
Join Date: Apr 07
Posts: 354
LuxCoder is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

@JM

Hi i tried your codes to retrieve and update data in my textbox which is bound to a field in database. When i launch the application the textbox does not display the data?? can you tell me what could be possibly wrong??

vb Code:
  1. Private connection As New SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ProjectMW\MachineWale\MachineWale\DatabaseMW.mdf;Integrated Security=True;User Instance=True")
  2.     Private adapter As New SqlClient.SqlDataAdapter("SELECT kmsrun FROM machineprofile", connection)
  3.     Private table As New DataTable
  4. Private Sub InitialiseDataAdapter()
  5. Dim update As New SqlClient.SqlCommand("UPDATE machineprofile SET kmsrun = '" & TextBox10.Text & "' WHERE MachineID = '" & TextBox1.Text & "'", Me.connection)
  6. Me.adapter.UpdateCommand = update
  7.         Me.adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
  8.  
  9. Private Sub GetData()
  10.        
  11.         Me.adapter.Fill(Me.table)
  12.  
  13. End Sub
  14.  
  15. Private Sub SaveData()
  16.                Me.adapter.Update(Me.table)
  17. End Sub
LuxCoder is offline   Reply With Quote
Old Oct 31st, 2009, 02:49 PM   #21
LuxCoder
Hyperactive Member
 
Join Date: Apr 07
Posts: 354
LuxCoder is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

anyone plz help!! y is this not working?
LuxCoder is offline   Reply With Quote
Old Oct 31st, 2009, 04:51 PM   #22
LuxCoder
Hyperactive Member
 
Join Date: Apr 07
Posts: 354
LuxCoder is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

I tried this piece of code to update the datarow where value of the MachineID is textbox1.text

vb Code:
  1. Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
  2.         Using connection As New SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ProjectMW\MachineWale\MachineWale\DatabaseMW.mdf;Integrated Security=True;User Instance=True")
  3.             Using command As New SqlClient.SqlCommand("INSERT INTO MachineProfile ([MachineID], [Category], [kmsrun]) VALUES (@MachineID, @Category, @kmsrun)  where [MachineID] = '" & TextBox1.Text & "'", connection)
  4.                 command.Parameters.AddWithValue("@MachineID", TextBox1.Text)
  5.                 command.Parameters.AddWithValue("@Category", ComboBox2.Text)
  6.                 command.Parameters.AddWithValue("@kmsrun", TextBox10.Text)
  7.                 connection.Open()
  8.                 command.ExecuteNonQuery()
  9.              End Using
  10.         End Using
  11.     End Sub

And i am getting this error:

Quote:
Incorrect syntax near the keyword 'where'.
What's wrong??
LuxCoder is offline   Reply With Quote
Old Oct 31st, 2009, 08:35 PM   #23
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

@LuxCoder

With regards to post #20, are you actually calling those methods at all, i.e. are you actually getting any data? Even if you are, are you binding your DataTable to your TextBox? If you don't retrieve data and put it into the TextBox then the TextBox won't show any data.

With regards to post #21, please do not EVER bump a thread like that but especially not someone else's CodeBank thread. Please don't clutter up the useful information with pointless bumps that are against forum rules.

With regards to post #22, you've got a syntax error in your SQL because you've got an INSERT statement with a WHERE clause. Have you read the information provided in this thread? Look at the syntax used for INSERT and UPDATE statements. INSERT is used to add a new record while UPDATE is used to edit an existing record. Work out which one it is that you want to do and use the appropriate SQL syntax.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Dec 29th, 2009, 11:25 AM   #24
riechan
Addicted Member
 
riechan's Avatar
 
Join Date: Feb 08
Location: Japan
Posts: 214
riechan is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

Question, in this line of code:

Code:
dbAdpPatronType.Fill(dbDsetPatron, "PatronType")
Is the syntax like this:
[adaptername].fill([datasetname],[datatablename?])
__________________
ほんとにどもありがとう!
riechan is offline   Reply With Quote
Old Dec 29th, 2009, 11:40 AM   #25
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by riechan View Post
Question, in this line of code:

Code:
dbAdpPatronType.Fill(dbDsetPatron, "PatronType")
Is the syntax like this:
[adaptername].fill([datasetname],[datatablename?])
Strictly, no. It's:
vb.net Code:
  1. dataAdapter.Fill(dataSet, "DataTableName")
"Name" implies a string containing a name and in that case the adapter and the data set are not the names of objects, but rather references to those objects.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Dec 29th, 2009, 11:48 AM   #26
riechan
Addicted Member
 
riechan's Avatar
 
Join Date: Feb 08
Location: Japan
Posts: 214
riechan is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

So then:

Code:
    Dim dbConn As New SqlConnection
    Dim dbAdp As SqlDataAdapter
    Dim dbDset As DataSet

        dbConn.ConnectionString = "Integrated Security=SSPI; Initial Catalog=DB; Persist Security Info=False;"
        dbConn.Open()

        dbAdp = New SqlClient.SqlDataAdapter("SELECT * FROM table", dbConn)
        dbDset = New DataSet
        dbAdp.Fill(dbDset, "Table")
"Table" in the dbAdp.fill creates a datatable named "Table", using the results of the query in dbAdp, and places the datatable into the dbDset, right? Meaning, it automatically creates a datatable name "Table" in the dbDset?
__________________
ほんとにどもありがとう!
riechan is offline   Reply With Quote
Old Dec 29th, 2009, 12:11 PM   #27
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by riechan View Post
So then:

Code:
    Dim dbConn As New SqlConnection
    Dim dbAdp As SqlDataAdapter
    Dim dbDset As DataSet

        dbConn.ConnectionString = "Integrated Security=SSPI; Initial Catalog=DB; Persist Security Info=False;"
        dbConn.Open()

        dbAdp = New SqlClient.SqlDataAdapter("SELECT * FROM table", dbConn)
        dbDset = New DataSet
        dbAdp.Fill(dbDset, "Table")
"Table" in the dbAdp.fill creates a datatable named "Table", using the results of the query in dbAdp, and places the datatable into the dbDset, right? Meaning, it automatically creates a datatable name "Table" in the dbDset?
That's correct.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Old Dec 29th, 2009, 12:17 PM   #28
riechan
Addicted Member
 
riechan's Avatar
 
Join Date: Feb 08
Location: Japan
Posts: 214
riechan is an unknown quantity at this point (<10)
Re: Retrieving and Saving Data in Databases

So then, how can I clear the contents of a single datatable in a dataset? I believe the dataset.clear() method clears the whole dataset, is there something like a datatable.clear()? And what would be the syntax for clearing a specific datatable, if there is such a method in .net?
__________________
ほんとにどもありがとう!
riechan is offline   Reply With Quote
Old Dec 29th, 2009, 09:12 PM   #29
jmcilhinney
.NUT
 
jmcilhinney's Avatar
 
Join Date: May 05
Location: Sydney, Australia
Posts: 54,910
jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)jmcilhinney has a reputation beyond repute (3000+)
Re: Retrieving and Saving Data in Databases

Quote:
Originally Posted by riechan View Post
So then, how can I clear the contents of a single datatable in a dataset? I believe the dataset.clear() method clears the whole dataset, is there something like a datatable.clear()? And what would be the syntax for clearing a specific datatable, if there is such a method in .net?
Please don't clutter up Codebank threads with every question you may have that's remotely related to the topic. This stuff belongs in a new thread of your own in the VB.NET forum. Only post to a CodeBank thread if you have a question that relates specifically to the information originally posted; otherwise CodeBank threads become less useful because finding relevant information is harder.

As for the question, have you read the documentation? That should ALWAYS be your first source of information. If you want to do something with a DataTable then read the documentation for the DataTable class. That will tell you definitively whether there's a DataTable.Clear method.
__________________

2007, 2008, 2009, 2010

Why is my data not saved to my database? | Communicating between multiple forms | MSDN Data Walkthroughs
MSDN "How Do I?" Videos: VB | C#
VBForums Database Development FAQ
My CodeBank Submissions: VB | C# (ForumAccount has translated some of my VB submissions to C#)
My Blog: Defining and Raising Custom Events | Manipulating GDI+ Drawings | Using Parameters in ADO.NET
jmcilhinney is online now   Reply With Quote
Reply

Go Back   VBForums > VBForums CodeBank > CodeBank - Visual Basic .NET


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -5. The time now is 02:30 AM.




To view more projects, click here

Acceptable Use Policy


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.