Database column creation through ADOX.Table - vb.net

I'm trying to create columns in an existing access database. The database has already been created, it contains the empty table named "table1", but it does not contain any columns, now I want to add a column into it. But it produces some error.
Arguments are of the wrong type, are out of acceptable range, or are
in conflict with one another.
Imports ADOX
Imports ADOX.DataTypeEnum
Imports ADOX.KeyTypeEnum
Imports System.Data.OleDb
Imports System.Data.SqlClient
Dim database_location As String = Application.UserAppDataPath
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
insert_columns("DB3", "table1", "Key", adInteger, True, True)
End Sub
Function insert_columns(ByRef Database_file_name As String, ByRef table_name As String, ByRef column_name As String, ByRef data_type As ADOX.DataTypeEnum, Optional ByRef primary_key As Boolean = False, Optional ByRef auto_increment As Boolean = False)
Dim DB_file_name As String = "\" & Database_file_name & ".mdb"
Dim catDB As ADOX.Catalog
Dim tblNew As ADOX.Table
' Dim catstring As String
'Try
catDB = New ADOX.Catalog
' Open the catalog.
catDB.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & database_location & DB_file_name
tblNew = New ADOX.Table
' Create a new Table object.
With tblNew
.Name = table_name
.ParentCatalog = catDB
' Create fields and append them to the
' Columns collection of the new Table object.
With .Columns
.Append(column_name, data_type)
If auto_increment = True Then
.Item(column_name).Properties("AutoIncrement").Value = True
End If
If primary_key = True Then
tblNew.Keys.Append("PrimaryKey", KeyTypeEnum.adKeyPrimary, column_name)
End If
End With
End With
' Add the new Table to the Tables collection of the database.
catDB.Tables.Append(tblNew)
'clean up
catDB = Nothing
tblNew = Nothing
Return True
'Catch ex As Exception
' error_entry("Column creation error. Database name: " & DB_file_name & " Column Name: " & column_name & vbNewLine & ex.Message)
' Return False
'End Try
End Function

Argh, didn't read properly that you are using adox. I'll leave the answer just in case.
I used ACE but it should be the same:
Using cmd As New OleDb.OleDbCommand() 'Creates table and columns in it
cmd.Connection = <your connection>
cmd.CommandText = "CREATE TABLE [" & <table_name> & "]([<column_name>] <COLUMN TYPE>, ...repeat)" ' so it looks like "CREATE TABLE [NewTable]([Column1] TEXT, [Columnnnnz2] INTEGER)
cmd.ExecuteNonQuery()
End Using
If you want to add columns independently then Add columns to an Access (Jet) table from .NET

Related

How to split a joined column into its seperate columns and use the data? (VB.Net + SQL Management Studio)

This is gonna be somewhat tricky to explain but I'll try to break it down. Note that this is created using VB.Net 2003.
I have a Web page which requires user to input data to save into SQL. They are required to fill in:
Course: {Select via drop-down table} \\ Variable name = Crse
Emp No: {Manually type the number} \\ Variable name = Emp
For the drop down list for Course, the data is obtained from an SQL table 'Course', with the columns:
| Course Code | Course Title |
Once input complete, I can then save the entry into my Emp_Course table in SQL using the query:
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"Crse.SelectedItem.ToString & "')"
Previously the drop-down list only needed the show Course Code, but now I'm required to add in the Course Title as well. Another thing to point out is that the Course Code has no fixed length.
Drop-down list sample:
Before:
A001
BX003
After:
A001 - Course A
BX003 - Course BX
Meaning I have to change the logic in populating the drop-down list:
Dim list As New SqlCommand("select CourseCode + ' - ' " _
& "+ CourseTitle as Course from [SQL].[dbo].[Course] " _
& "order by CourseCode", SQLDB)
Now comes my main issue, when I want to save my entry, the program obviously gives an error because the SQL still refers to the Course Code only, while my drop-down list is a Code + Description hybrid.
So since now I've made my course selection, how am I supposed to add to my SQL to update Emp_Course table to tell it to select the Course Code part of my hybrid selection?
I would just go to the Course table and just add a new Code + Title column and refer to that, but I have no authority to modify it and need to work around it.
Any other alternatives I can use?
Dim arr As String() = Crse.SelectedItem.ToString().Split(New Char() {"-"c})
Dim courseCode AS String = Trim(arr(0))
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"courseCode & "')"
Comments and explanations in line.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Crse.DataSource = CreateDataSource()
'Course is the concatenated string returned from
'the database containing the CourseCode and the CourseTitle
Crse.DataTextField = "Course"
Crse.DataValueField = "CourseCode"
Crse.DataBind()
Crse.SelectedIndex = 0
End If
End Sub
Protected Function CreateDataSource() As DataTable
Dim dt As New DataTable
Using SQLDB As New SqlConnection("Your connection string")
'This selects the CourseCode as a separate column and the string called Course
'containing the CourseCode and the CourseTitle
Using cmd As New SqlCommand("select CourseCode, CourseCode + ' - ' + CourseTitle as Course from [SQL].[dbo].[Course] order by CourseCode", SQLDB)
SQLDB.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Protected Sub UpdateDatabase()
Using SQLDB As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("insert into EMP_COURSE (Employee_No, CourseCode) values(#EmpNo, #CourseCode);", SQLDB)
'I guessed at the SqlDbType. Check the database for the real data types.
cmd.Parameters.Add("EmpNo", SqlDbType.Int).Value = CInt(Emp.Text)
'Always use parameters to prevent SQL injection
'The SelectedValue will return the CourseCode
cmd.Parameters.Add("#CourseCode", SqlDbType.VarChar).Value = Crse.SelectedValue
SQLDB.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateDatabase()
End Sub
End Class
Split the value and get the course code as in the following code. Hope it helps.
Dim Str = Crse.SelectedItem.ToString
Dim strArr() As String
strArr = Str.Split(CType("-", Char()))
Dim CourseCode As String = strArr(0).Trim

Update record in DataGridView

I use simple SQL to modyf ACC database conected to DataGridView via dataSet.xsc. Inserting works perfect, but updateing is fail (why?)
Table have 3 columns (2 strings and one boolean represented by Checkbox).
UPDATE Tabele
SET We = True 'or False in another SQL
WHERE (Name = ?) AND (Address = ?)
"We" is checkbox in table column, I try change by mouse in DataGridView.
In code i used this line to modyf table:
Private Sub Tabela_adresowDataGridView_CellContentClick(sender As Object, _
e As Windows.Forms.DataGridViewCellEventArgs) Handles _
Tabela_adresowDataGridView.CellContentClick
If e.ColumnIndex = 2 Then
Try
With Tabela_adresowDataGridView
Me.Tabela_adresowBindingSource.EndEdit()
If .Item(e.ColumnIndex, e.RowIndex).Selected = True Then
Me.Tabela_adresowTableAdapter.UpdateQuery_Checked(.Item(0, e.RowIndex).Value.ToString, _
.Item(1, e.RowIndex).Value.ToString)
Else
Me.Tabela_adresowTableAdapter.UpdateQuery_Uncheck(.Item(0, e.RowIndex).Value.ToString, _
.Item(1, e.RowIndex).Value.ToString)
End If
Tabela_adresowDataGridView.Update()
'Me.Validate()
'Me.TableAdapterManager.UpdateAll(Me.Baza_adresowDataSet)
'Baza_adresowDataSet.AcceptChanges()
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Regardless of whether the inserted Primarykey or use one simple SQL with 3th parameter for a check state. Table is not modyfied. (?)
Try to select your quert by you want and after put in your table:
Dim SelectQuery As String = "Your Query"
Dim WhereQuery As String = " WHERE (1=1)"
ElseIf BOX_toDate.Text <> Nothing Then
Name= WhereQuery & " AND TargetDate <= '" & Your value & "'"
End If
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con = FunctionConnection()
cmd.Connection = con
cmd.CommandText = SelectQuery & WhereQuery
cmd.CommandType = CommandType.Text
Or like that: How to search data in all tables in database using select query in vb.net?

how to call checkbox value from sql to display on form vb.net

am doing this but not working only apply in first record its working in insert and update
i stored in sql as true or false
Sub db_load()
On Error Resume Next
Dim pringdata As String = "SELECT custcode_" & _
",custname_" & _
",custname2_" & _
",phone_" & _
",mobile_" & _
",custadd_" & _
",date_" & _
",cutomerzone_ " & _
",check_ " & _
" FROM custInfo "
Dim sqlconload As New SqlConnection(sqlcon)
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "custInfo")
For i As Integer = ds.Tables(0).Rows.Count = 0 To -1
If ds.Tables(0).Rows(i).Item("check_") = "true" Then
checkActive.Checked = True
Else
checkActive.Checked = False
End If
Next
sqlconload.Close()
I gather you are referring to a specific customer since you're only setting a single checkbox? You'll need to modify your query to match that.
Next, examine how you're storing the "check" column. In most cases, converting to Bool will resolve it but you may have to special case it based on available values.
Also, if the field you're looking at could be null, you'll have to account for that as well.
Here's a good pattern to follow that properly disposes of resources such as connections, commands, and readers.
Public Sub db_load()
Using cn = New SqlConnection(sqlcon)
cn.Open()
Using cmd = New SqlCommand("SELECT custcode,custname,custname2,phone,mobile,custadddate,customerzone,check FROM custInfo", cn)
Using dr = cmd.ExecuteReader()
If dr.Read Then
checkActive.Checked = CBool(dr("check"))
End If
End Using
End Using
End Using
End Sub

Creating Relationships in Access

I got two tables in my access file. and I would like to create relationship between them. The following diagram is the relationship I created manually in Access.
However, I want to create the relationships in VB.net and here is my code:
conn.Open()
daBooks = New OleDb.OleDbDataAdapter("SELECT * FROM Books", conn)
daAuthor = New OleDb.OleDbDataAdapter("SELECT * FROM authors", conn)
daBooks.Fill(ds, "Books")
daAuthor.Fill(ds, "authors")
conn.Close()
'Set the relation
Dim parentColumn As DataColumn
parentColumn = ds.Tables("authors").Columns("AuthorID")
Dim childColumn As DataColumn = New DataColumn
Try
childColumn = ds.Tables("Books").Columns("AuthorID")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
Dim a As String
a = ds.Tables("authors").Rows(0).Item("AuthorID")
Dim b As String
b = ds.Tables("Books").Rows(0).Item("AuthorID")
Dim relation As DataRelation = New _
System.Data.DataRelation("Books_Authors", parentColumn, childColumn)
ds.Relations.Add(relation)
RelationName.Text = relation.RelationName
'End of setting relation
Dim cb1 As New OleDb.OleDbCommandBuilder(daBooks)
Dim cb2 As New OleDb.OleDbCommandBuilder(daAuthor)
Try
daBooks.Update(ds, "books")
Catch ex As Exception
MsgBox(ex.Message)
End Try
daAuthor.Update(ds, "authors")
However after I ran the code, it couldn't change the database. Can anyone help me with this so that I can create a new relationship for two tables in VB.NET.
Generally I think the problem is that the System.Data.DataRelation and ds.Relations.Add(relation) just create the relationship for the dataset but it hasn't been updated to the database through dataadapter or something else. Am I correct by saying so or it's because of other reasons. If I'm correct, then how to update the dataset to database?
You can create that relationship by executing an ALTER TABLE statement from your OleDb connection.
ALTER TABLE Books
ADD CONSTRAINT BooksRelationship
FOREIGN KEY (AuthorID) REFERENCES Authors (AuthorID);
You can create a macro in Access that creates a relationship between your tables and run it via VB.NET.
Here is a function to create a relation in MS Access:
Public Function MacroCreateRelation()
Dim db As DAO.Database
CreateRelation("Author", "IdAuthor", _
"Book", "IdAuthor")
Set db = Nothing
End Function
Private Function CreateRelation(primaryTblName As String, _
primaryFieldName As String, _
foreignTblName As String, _
foreignFieldName As String) As Boolean
On Error GoTo ErrHandler
Dim myDB As DAO.Database
Dim newRelation As DAO.Relation
Dim relatingField As DAO.Field
Dim relationName As String
relationName = primaryTblName + "_" + primaryFieldName + _
"__" + foreignTblName + "_" + foreignFieldName
Set myDB = CurrentmyDB()
' First create the relation
Set newRelation = myDB.CreateRelation(relationName, _
primaryTblName, foreignTblName)
'field of the primary table
Set relatingField = newRelation.CreateField(primaryFieldName)
'Then the field of the the second table
relatingField.ForeignName = foreignFieldName
'now just add the field to the relation
newRelation.Fields.Append relatingField
'Last but not least add the relation to the db
myDB.Relations.Append newRelation
Set myDB = Nothing
return True
Exit Function
ErrHandler:
Debug.Print Err.Description + " [ " + relationName + "]"
return False
End Function
Then you have just to call the macro from VB.NET.

easiest way to add a SQL column through VB

What i want to do is first check if a certain column already exists in a table and if not add it. I want to implement this through visual basic. If somebody took a little time to comment and briefly explain each step i would greatly appreciate it.
There are two ways to determine if a column exists: either try to use it and catch the error if it doesn't exist, or read the metadata from the database see SQL Server: Extract Table Meta-Data (description, fields and their data types)
Once you know that you need to add the column you use the ALTER TABLE command to add the column to the table.
Here is vb.net script to check if column exist, if not, create it..
''' summary
''' Checks to see if a table exists in Database or not.
'''
''' Table name to check
''' Connection String to connect to
''' Works with Access or SQL
'''
Public Function DoesTableExist(ByVal tblName As String, ByVal cnnStr As String) As Boolean
' For Access Connection String,
' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
' accessFilePathAndName
' Open connection to the database
Dim dbConn As New OleDbConnection(cnnStr)
dbConn.Open()
' Specify restriction to get table definition schema
' For reference on GetSchema see:
' http://msdn2.microsoft.com/en-us/library/ms254934(VS.80).aspx
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = dbConn.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
'Table does not exist
DoesTableExist = False
Else
'Table exists
DoesTableExist = True
End If
dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()
End Function
'''
''' Checks to see if a field exists in table or not.
'''
''' Table name to check in
''' Field name to check
''' Connection String to connect to
'''
'''
Public Function DoesFieldExist(ByVal tblName As String, _
ByVal fldName As String, _
ByVal cnnStr As String) As Boolean
' For Access Connection String,
' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
' accessFilePathAndName
' Open connection to the database
Dim dbConn As New OleDbConnection(cnnStr)
dbConn.Open()
Dim dbTbl As New DataTable
' Get the table definition loaded in a table adapter
Dim strSql As String = "Select TOP 1 * from " & tblName
Dim dbAdapater As New OleDbDataAdapter(strSql, dbConn)
dbAdapater.Fill(dbTbl)
' Get the index of the field name
Dim i As Integer = dbTbl.Columns.IndexOf(fldName)
If i = -1 Then
'Field is missing
DoesFieldExist = False
Else
'Field is there
DoesFieldExist = True
End If
dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()
End Function
Dim connString As String = "Data Source=NameOfMachine\InstanceofSQLServer;Initial Catalog=NameOfDataBase;Integrated Security=True"
Dim MyCol As String = "NameOfColumn"
Dim MyTable As String = "[NameOfTable]" ' or "[Name Of Table]" use brackets if table name contains spaces or other illegal Characters
Dim MySql As String = "IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS" & vbCrLf &
"WHERE TABLE_NAME = '" & MyTable & "' AND COLUMN_NAME = '" & MyCol & "')" & vbCrLf &
"BEGIN" & vbCrLf &
"ALTER TABLE [dbo]." & MyTable & " ADD" & vbCrLf & "[" & MyCol & "] INT NULL ;" & vbCrLf & "END"
Try
' MsgBox(MySql)- this msg box shows the Query so I can check for errors- Not required for code.
Dim dbConn = New SqlConnection(connString)' Note ConnString must be declared in the form class or within this Sub. Connstring is your connection string
Dim dbCmd = New SqlCommand(MySql, dbConn)
dbConn.Open()
dbCmd.ExecuteNonQuery()
'MessageBox.Show("Ready To Load Addendums")
dbConn.Close()
Catch ex As Exception
MsgBox("We've encountered an error;" & vbCrLf & ex.Message)
End Try