I have problem with my code which fills multi tables into my dataset. It loads all contents contained in tables of my database to only one table in dataset. My code is shown below. How to load those tables from database into a dataset , that has the same number of tables and contents.
Private Sub Filldataset()
Private cnn As OleDbConnection
Private dt As New DataTable
Private da As New OleDbDataAdapter
Private cmd As New OleDbCommand
Private ds As New DataSet
Dim tblrestrictions As String() = New String() {Nothing, Nothing, Nothing, "TABLE"}
Dim userTables As DataTable = Nothing
userTables = cnn.GetSchema("Tables", tblrestrictions)
Dim i As Integer
For i = 1 To userTables.Rows.Count - 1 Step 1
cnn = New OleDbConnection(Str)
cnn.Open()
cmd = cnn.CreateCommand
cmd.CommandText = "select * from" & " " & userTables.Rows(i)(2).ToString
dt.Clear()
da.SelectCommand = cmd
da.Fill(dt)
da.Fill(ds)
Next
cnn.Close()
MessageBox.Show(ds.Tables.Count)
End Sub
Connections can be created elsewhere but should not be opened or closed until directly before an directly after you use them. You will have to adjust this code for an Oledb application.
Private Sub GetData()
cn.Open()
Dim dt As DataTable = cn.GetSchema("Tables")
cn.Close()
Dim ds As New DataSet
Dim row As DataRow
For Each row In dt.Rows
Dim strTableName As String = row(2).ToString
Dim strSQL As String = "Select * From " & strTableName
Dim cmd As New SqlCommand(strSQL, cn)
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(ds, strTableName)
Next
Debug.Print(ds.Tables.Count.ToString)
End Sub
I scoped several variables locally that you will want to scope to the class like the dataset
Related
I'm trying to search a date using DateTimePicker in an Access database and have the results show in the DataGridView but it doesn't work. No errors but it just doesn't show the database/results. Here's pictures of the database and the debugged form when it doesn't work in case they are of any use:
and here's my code:
Imports System.Data.OleDb
Public Class Form10
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Sales.accdb;")
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dt1 As DateTime = DateTime.Parse(DateTimePicker1.Value)
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("MM/dd/yyyy"), connection)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
DataGridView2.DataSource = da
connection.Close()
End Sub
Private Sub Form10_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
End Class
Use the true date value of the datetime picker:
Dim dt1 As DateTime = DateTimePicker1.Value
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("yyyy'/'MM'/'dd") & "#", connection)
I'm trying to use an autocomplete textbox, fed from a SQL Serve .mdf database file.
This is my code:
Dim cmd As New SqlCommand("Select col_name FROM college ", cn)
If cn.State = ConnectionState.Closed Then cn.Open()
Dim ds As New DataSet
Dim sqda As New SqlDataAdapter(cmd)
sqda.Fill(ds, "college")
Dim col As New AutoCompleteStringCollection
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count - 1
col.Add(ds.Tables(0).Rows(i)("col_name").ToString())
Next
TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource
TextBox1.AutoCompleteCustomSource = col
TextBox1.AutoCompleteMode = AutoCompleteMode.Suggest
Since I am using SQL Server, the data not showing in the list.
I think its needs to use character N like
Insert data into SQL Server as:
cmd = New SqlCommand("insert into college (col_name) values (N'" & TextBox1.Text.Trim & "')", cn)
Keep your database objects local so you can control the closing and disposing. Using...End Using blocks handle this even if there is an error.
Always use parameters to avoid Sql injection.
In .net Char supports Unicode so strings (which are arrays of Char) also support Unicode. As long as the field in Sql Server is of type NVarChar. I don't see a problem
Private Sub SetUpAutoComplete()
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("Select col_name FROM college ", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Dim col As New AutoCompleteStringCollection
For Each row As DataRow In dt.Rows
col.Add(row("col_name").ToString)
Next
'Just to check if we have some data
Debug.Print(col.Count.ToString)
TextBox3.AutoCompleteSource = AutoCompleteSource.CustomSource
TextBox3.AutoCompleteCustomSource = col
TextBox3.AutoCompleteMode = AutoCompleteMode.Suggest
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetUpAutoComplete()
End Sub
Private Sub InsertCollege()
Using cn As New SqlConnection("Your Connection string")
Using cmd As New SqlCommand("insert into college (col_name) values (#Name)", cn)
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox1.Text.Trim
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
My script does not insert any data in the database table and it does not throw any error either.
The server, database and table names are correct.
The workbook is selected using filedialog (hence correct filepath) and the worksheet name seems correct too.
I have data in column A. My table is made of 2 fields:
ID (Identity, autocrement)
CustomerName
The While Loop performs 2 iterations but I have 4 records on the worksheet.
Any idea why the data does not insert in the table?
'Open the dialog box to select the file to upload
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.InitialDirectory = "C:\"
fd.Filter = "Excel Files|*.xlsx"
fd.FilterIndex = 2
fd.RestoreDirectory = True
'declare variables - edit these based on your particular situation
Dim ssqltable As String = "tbl1"
Dim myexceldataquery As String = "select CustomerName from [A$]"
'create our connection strings
Dim sexcelconnectionstring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=Excel 12.0;"
Dim ssqlconnectionstring As String = "Data Source=AA1\SQL001_DEV001;Initial Catalog=DB_Test;Integrated Security=True"
'execute a query to erase any previous data from our destination table
Dim sclearsql As String = Convert.ToString("delete from ") & ssqltable
Dim sqlconn As New SqlClient.SqlConnection(Connections.MyMainSQLServer)
Dim sqlcmd As New SqlCommand(sclearsql, sqlconn)
sqlconn.Open()
sqlcmd.ExecuteNonQuery()
sqlconn.Close()
'series of commands to bulk copy data from the excel file into our sql table
Dim oledbconn As New OleDbConnection(sexcelconnectionstring)
Dim oledbcmd As New OleDbCommand(myexceldataquery, oledbconn)
oledbconn.Open()
Dim dr As OleDbDataReader = oledbcmd.ExecuteReader()
Dim bulkcopy As New SqlBulkCopy(ssqlconnectionstring)
bulkcopy.DestinationTableName = ssqltable
While dr.Read()
bulkcopy.WriteToServer(dr)
End While
dr.Close()
oledbconn.Close()
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyExcelSpreadsheet.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=MMSQL1;Initial Catalog=DbName; User Id=UserName; Password=password;"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLConn)
bulkCopy.DestinationTableName = "TableToWriteToInSQLSERVER"
Try
objDR = objCmdSelect.ExecuteReader
bulCopy.WriteToServer(objDR)
objDR.Close()
SQLConn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
I'm working on a login system with a password reset feature. i'm trying to figure out how to output the secret question from a matched username. my idea was to get the row index of the matched username then then output the question using the row index. also is it possible to put the returned row index in a variabale? i'm kinda new to vb.net soooo if you have better ideas let me know and i'll thank you in return :P
Dim con As SqlConnection
Dim command As SqlCommand
Dim ad As SqlDataAdapter
Dim ds As DataSet
Public constring As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\almond\Desktop\Ticket System\Ticket System\Database.mdf;Integrated Security=True;User Instance=True"
If TextBox1.Text = "" Then
MessageBox.Show("Please enter your username")
End If
Dim q2 As String = "SELECT * FROM tblusers WHERE username = #username "
con = New SqlConnection
con.ConnectionString = constring
con.Open()
Dim command As New SqlCommand(q2, con)
command.Parameters.Add("#username", SqlDbType.NChar).Value = TextBox1.Text
Dim ad As New SqlDataAdapter(command)
ad = New SqlDataAdapter(command)
Dim table As New DataTable
ad.Fill(table)
If table.Rows.Count() = 0 Then
MessageBox.Show("Account Not Found")
Exit Sub
End If
con.Close()
End Sub
Trying to get this bit of code to enter a player name fill it in the datarow then update it in the DB. It currentley updates in the datarow but I can not get the code right to update the DB. Could you please help cheers.
Using da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM Team1", con)
da.Fill(ds, "BPAWA")
txtFirstName.Text = ds.Tables("BPAWA").Rows(0).Item(1)
T1P1 = InputBox("Name of Player 1")
ds.Tables("BPAWA").Rows(0).Item(1) = T1P1
ds.Tables("BPAWA").AcceptChanges()
ds.AcceptChanges()
da.Update(ds, "BPAWA")
MsgBox("Player 1 Added Successfully")
End Using
You OleDbDataAdapter is not linked to an actual command neither you seem to have created the adapter in your code. See an example here
Missing a line like this
Dim da As OleDbDataAdapter = new OleDbDataAdapter(selectCommand, connection);
so I could rewrite your code in this way (Avoiding the global variables)
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim dbProvider As String = "PROVIDER=microsoft.ace.oledb.12.0;"
Dim dbSource As String = "Data Source = C:\BP_Table_Project.accdb"
Dim ds as DataSet = new DataSet()
Using con As OleDbConnection = new OleDbConnection()
con.ConnectionString = dbProvider & dbSource
con.Open()
MsgBox("Connection With Database Established", 0, "Database Connection")
Using da as OleDbDataAdapter = new OleDbDataAdapter("SELECT * FROM Team1", con)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "BPAWA")
......
da.Update(ds, "BPAWA")
MsgBox("Player 1 Added Successfully")
End Using
MsgBox("Connection With Database Closed", 0, "Database Connection")
End Using
End Sub
Before da.Update(ds, "BPAWA")
Add:
ds.Tables("BPAWA").AcceptChanges()
ds.AcceptChanges()