Naming a access Table From textbox's text - vb.net

I am Trying to create New access table in a database but when i try to name it from text box it is giving an error
Sub CreateTable()
Dim strCreate As String = "CREATE TABLE" & TxtBoxTblName.Text &(" & _
"CountryName varchar(120) Primary key," & _
"Continent Integer," & _
"Area Long," & _
"Population Long," & _
"Capital varchar(80)," & _
"Code char(2));"
Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source=""Data Source=" & filename & ".mdb;")
Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)
conDatabase.Open()
cmdDatabase.ExecuteNonQuery()
conDatabase.Close()
MessageBox.Show("Table Created Sucessfully")
End Sub

I guess you missed a " in this line "CREATE TABLE" & TxtBoxTblName.Text &(" & _ and these in no space after CREATE TABLE keyword that will also yields error. so it should be "CREATE TABLE " & TxtBoxTblName.Text &"(" & _ See the difference here or try below code
Dim STR_DDL As String
STR_DDL = "CREATE TABLE #TABLENAME# (CountryName varchar(120) Primary key,Continent Integer,Area Long,Population Long,Capital varchar(80),Code char(2));"
STR_DDL.Replace("#TABLENAME#", Trim(TxtBoxTblName.Text))
OR
using Composite Formatting
Dim STR_DDL As String = String.Format("CREATE TABLE {0} (CountryName varchar(120) Primary key " & _
",Continent Integer,Area Long,Population Long,Capital varchar(80) " & _
",Code char(2));", Trim(TxtBoxTblName.Text))
{0} is a place holder for TxtBoxTblName.Text
and use it
Dim cmdDatabase As OleDbCommand = New OleDbCommand(STR_DDL , conDatabase)

Related

How to CREATE TABLE using sql/VBA in excel with ADO

I'm trying to erase table content and replace it with new content in an excel sheet.
The code doesn't raise any errors however everytime I run it, it inserts some blanck cells before the source table.
The 'base.xlsx' table sheet looks like this :
If target.xlsx is void before running the code I get what I want however if I run it again I get this :
Here is the code :
Sub SQLQUERY()
Dim Cn As ADODB.Connection
Dim QUERY_SQL As String
Dim ExcelCn As ADODB.Connection
SourcePath = "C:\Path\to\base.xlsx"
TargetPath = "C:\Path\to\target.xlsx"
CHAINE_HDR = "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] "
Set Cn = New ADODB.Connection
STRCONNECTION = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & SourcePath & "';" & _
"Mode=Read;" & _
"Extended Properties=""Excel 12.0;"";"
Colonnes = "[Col#1], Col2"
QUERY_SQL = _
"SELECT " & Colonnes & " FROM [base$] " & _
"IN '" & SourcePath & "' " & CHAINE_HDR
MsgBox (QUERY_SQL)
Cn.Open STRCONNECTION
Set ExcelCn = New ADODB.Connection
ExcelCn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & TargetPath & ";" & _
"Extended Properties=""Excel 12.0;HDR=YES;"""
ExcelCn.Execute "DROP TABLE [sheet$]"
ExcelCn.Execute "CREATE TABLE [sheet$] ([C1] Float, [C2] Float, [C3] Float)"
Cn.Execute "INSERT INTO [sheet$] (C1, C3) IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL
'--- Fermeture connexion ---
Cn.Close
ExcelCn.Close
End Sub
After some research I discovered what's going on with the code. When Drop Table is executed Excel keep the "active range" and thus INSERT INTO will insert data after the active range.
To counter this we need to specify a range with the table name :
ExcelCn.Execute "DROP TABLE [sheet$]"
ExcelCn.Execute "CREATE TABLE [sheet$] ([C1] Float, [C2] Float, [C3] Float)"
Cn.Execute "INSERT INTO [sheet$A1:ZZ1] (C1, C3) IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL
'--- Fermeture connexion ---
Note the [sheet$A1:ZZ1] in the sql statement.

VB.Net-How to get Oledb Command from Text Box

I am running this code,its ok...
Sub CreateTable()
Dim strCreate As String = "CREATE TABLE Info(" & _
"CountryName varchar(120) Primary key," & _
"Continent Integer," & _
"Area Long," & _
"Population Long," & _
"Capital varchar(80)," & _
"Code char(2));"
Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source= " & filepath & ";")
Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)
conDatabase.Open()
cmdDatabase.ExecuteNonQuery()
conDatabase.Close()
But When I am doing same through TextBox,its not working
Sub CreateTable()
Dim strCreate As String = TextBox1.Text 'TextBox Contains Create table command
Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
"Data Source= " & filepath & ";")
Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)
conDatabase.Open()
cmdDatabase.ExecuteNonQuery
conDatabase.Close()
Whats wrong here??

creating tables in Access using VB.NET

I'm having trouble creating Access tables from VB.NET.
This is the code I have come up with but I keep getting errors:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'connection string
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
Dim my_connection As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\GhostDrive\Desktop\database.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim source As String
'query string
Dim my_query As String = "CREATE TABLE " & TextBox2.Text & " ( " & _
"ID Counter, " & _
"Year datetime," & _
"Title varchar(40)," & _
"image1 Long," & _
"Image2 Long," & _
"Image3 Long," & _
"Image4 Long," & _
"Serial varchar(20)," & _
"Purchaseprice Currency," & _
"Evalprice Currency, " & _
"Datepurchase DateTime, " & _
"Dateeval DateTime, " & _
"Sign varchar(40), " & _
"Grading varchar(20)," & _
"Eval YesNo, " & _
"Star YesNo, " & _
"Folder YesNo, " & _
"Forsale YesNo, " & _
"Error YesNo, " & _
"Barcode(varchar(20)," & _
"Comm YesNo )"
'create a connection
Dim my_dbConnection As New OleDbConnection(my_connection)
'create a command
Dim my_Command As New OleDbCommand(my_query, my_dbConnection)
'connection open
my_dbConnection.Open()
'command execute
my_Command.ExecuteNonQuery()
'close connection
my_dbConnection.Close()
ListBox1.Items.Clear()
source = TextBox1.Text
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source
Dim restrictions() As String = New String(3) {}
restrictions(3) = "Table"
connection.Open()
' Get list of user tables
userTables = connection.GetSchema("Tables", restrictions)
connection.Close()
' Add list of table names to listBox
Dim i As Integer
For i = 0 To userTables.Rows.Count - 1 Step i + 1
ListBox1.Items.Add(userTables.Rows(i)(2).ToString())
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
if i take all them out except ID it works and then i add them on by on back it stops "Year datetime," & _
YEAR is a reserved word in Access SQL. If I try to run the following code ...
Dim connectionString As String = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Users\Public\mdbTest.mdb;"
Using con As New OleDbConnection(connectionString)
con.Open()
Using cmd As New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "CREATE TABLE zzzTest (ID COUNTER, Year INTEGER)"
Try
cmd.ExecuteNonQuery()
Console.WriteLine("Table created.")
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
con.Close()
End Using
... I get
Syntax error in field definition.
However, if I enclose the field name in square brackets ...
cmd.CommandText = "CREATE TABLE zzzTest (ID COUNTER, [Year] INTEGER)"
... then I get
Table created.

Counter field in MS Access, how to generate?

How can I generate counter field like this 0001A, 0002A... becouse in standart it is 0,1,2,3,4.... how to change this?
Adding to #HansUp's excellent answer, you could hide the IDENTITY column and at the same time expose the formatted column using a SQL VIEW: you could then revoke privileges on the table so that users work with the VIEW and do not 'see' the table e.g. demo:
copy+paste into any VBA module, no references nor Access UI/object model required, creates a new mdb in the temp folder e.g. use Excel:
Sub YourView2()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE YourTable ( " & _
"ID INTEGER IDENTITY(1, 1) NOT NULL UNIQUE, " & _
"data_col VARCHAR(20) NOT NULL);"
.Execute Sql
Sql = _
"CREATE VIEW YourView AS " & _
"SELECT FORMAT$(ID, '0000') & 'A' AS formatted_ID, " & vbCr & _
" data_col " & vbCr & _
" FROM YourTable;"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('one');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('day');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('when');"
.Execute Sql
Sql = "SELECT * FROM YourView;"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString
End With
Set .ActiveConnection = Nothing
End With
End Sub
I think this one would be even better if you include DDL GRANT/REVOKE samples to manage the privileges
Here's the updated code to do just that:
Sub YourView2()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
Kill Environ$("temp") & "\DropMeToo.mdw"
On Error GoTo 0
' Create workgroup and db
Dim cat As ADOX.Catalog
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Jet OLEDB:Engine Type=4;" & _
"Data Source=" & _
Environ$("temp") & "\DropMeToo.mdw;" & _
"Jet OLEDB:Create System Database=-1"
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Jet OLEDB:Engine Type=4;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb;" & _
"Jet OLEDB:System Database=" & _
Environ$("temp") & "\DropMeToo.mdw;"
' Add table with data and user with privileges
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE YourTable ( " & _
"ID INTEGER IDENTITY(1, 1) NOT NULL UNIQUE, " & _
"data_col VARCHAR(20) NOT NULL);"
.Execute Sql
Sql = _
"CREATE VIEW YourView AS " & _
"SELECT FORMAT$(ID, '0000') & 'A' AS formatted_ID, " & vbCr & _
" data_col " & vbCr & _
" FROM YourTable WITH OWNERACCESS OPTION;"
.Execute Sql
.Execute "CREATE USER onedaywhen pwd Chri5tma5;"
.Execute "GRANT ALL PRIVILEGES ON YourView TO onedaywhen;"
.Execute "REVOKE ALL PRIVILEGES ON YourTable FROM onedaywhen;"
End With
End With
' Test user can connect
Dim con As ADODB.Connection
Set con = New ADODB.Connection
With con
.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Jet OLEDB:Engine Type=4;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb;" & _
"Jet OLEDB:System Database=" & _
Environ$("temp") & "\DropMeToo.mdw;" & _
"User ID=onedaywhen;Password=pwd;"
.Open
On Error Resume Next
' Attempt to insert to table (no privileges)
Sql = _
"INSERT INTO YourTable (data_col) VALUES ('one');"
.Execute Sql
If Err.Number <> 0 Then
MsgBox _
Err.Number & ": " & _
Err.Description & _
" (" & Err.Source & ")"
End If
On Error GoTo 0
Dim rs
On Error Resume Next
' Attempt to read table (no privileges)
Sql = _
"SELECT * FROM YourTable;"
Set rs = .Execute(Sql)
If Err.Number <> 0 Then
MsgBox _
Err.Number & ": " & _
Err.Description & _
" (" & Err.Source & ")"
End If
On Error GoTo 0
' From here, work only with VIEW
Sql = _
"INSERT INTO YourView (data_col) VALUES ('one');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('day');"
.Execute Sql
Sql = _
"INSERT INTO YourView (data_col) VALUES ('when');"
.Execute Sql
Sql = "SELECT * FROM YourView;"
Set rs = .Execute(Sql)
MsgBox rs.GetString
Set con = Nothing
End With
End Sub
The simplest solution would be to use a standard autonumber field (long integer). Let Access maintain those values for you. Then anytime you need those values in your "0001A" format, use the Format() function to add the leading zeros, and concatenate an "A".
This is trivially easy. If your autonumber field is named ID, you could do that transformation with this query:
SELECT Format(ID, "0000") & "A" AS formatted_ID
FROM YourTable;
Similarly you can apply the same expression to the control source property of a text box on a form or report.
One solution, that works for forms only!
create a GetId() function that calculates your counter (using DMax generally)
Use the Before insert event in your form to set the value of the field using GetId()
Drawback: in a multiuser environment, if another User2 starts addind a record after User1, but saves it before User1 saves his, there will be a duplicate problem. You will need to use the FormError event to regenerate the ID and resume the save process.

Create a SQL Table from Excel VBA

The problem is that I cannot get the table name that was entered into the variable, "tblName", to be used instead I get a correctly named database with a table named "tblName".
Is there some way to pick up the name in "tblName" or some way to change the name once it is created with a name th user enters?
Private Sub CreateDatabaseFromExcel()
Dim dbConnectStr As String
Dim Catalog As Object
Dim cnt As ADODB.Connection
Dim dbPath As String
Dim tblName As String
'Set database name in the Excel Sheet
dbPath = ActiveSheet.Range("B1").Value 'Database Name
tblName = ActiveSheet.Range("B2").Value 'Table Name
dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";"
'Create new database using name entered in Excel Cell ("B1")
Set Catalog = CreateObject("ADOX.Catalog")
Catalog.Create dbConnectStr
Set Catalog = Nothing
'Connect to database and insert a new table
Set cnt = New ADODB.Connection
With cnt
.Open dbConnectStr
.Execute "CREATE TABLE tblName ([BankName] text(50) WITH Compression, " & _
"[RTNumber] text(9) WITH Compression, " & _
"[AccountNumber] text(10) WITH Compression, " & _
"[Address] text(150) WITH Compression, " & _
"[City] text(50) WITH Compression, " & _
"[ProvinceState] text(2) WITH Compression, " & _
"[Postal] text(6) WITH Compression, " & _
"[AccountAmount] decimal(6))"
End With
Set cnt = Nothing
End Sub
Change this line:
.Execute "CREATE TABLE tblName ([BankName] text(50) WITH Compression, " & _
To this:
.Execute "CREATE TABLE " & tblName & " ([BankName] text(50) WITH Compression, " & _