creating tables in Access using VB.NET - 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.

Related

Fetch output of DBMS_OUTPUT.PUT_LINE in a VB .net application

I am trying to get a simple hello world output in vb from a pl/sql anonymous block
As far as I tried
Imports System.Data
Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oradb As String = "Data Source=(DESCRIPTION=" _
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=vmDA2D319)(PORT=1521))" _
+ "(CONNECT_DATA=(SERVICE_NAME=XE)));" _
+ "User Id=hr;Password=hr;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim cmd As New OracleCommand
cmd.Connection = conn
cmd.CommandText = "set server output on;" & vbNewLine & "DECLARE" & vbNewLine & "message varchar2(20):= 'Hello, World!'; " & vbNewLine & "BEGIN()" & vbNewLine & "dbms_output.put_line(message);" & vbNewLine & "END;" & vbNewLine & "/"
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
dr.Read()
Label1.Text = dr.ExecuteReader
conn.Dispose()
End Sub
End Class
Now this is the Part where I am stuck now. I just want fetch the output in a textbox actually.
But I am just trying to get the output in a label or maybe in a messagebox first.
UPDATE
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim oradb As String = "Data Source=(DESCRIPTION=" _
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=vmDA2D319)(PORT=1521))" _
+ "(CONNECT_DATA=(SERVICE_NAME=XE)));" _
+ "User Id=hr;Password=hr;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim cmd As New OracleCommand
cmd.CommandText = "set server output on;" & vbNewLine & "DECLARE" & vbNewLine & "return_value VARCHAR2(100) := 'Hello World!';" & vbNewLine & "get_status INTEGER;" & vbNewLine & "BEGIN" & vbNewLine & "DBMS_OUTPUT.GET_LINE (return_value, get_status);" & vbNewLine & "IF get_status = 0" & vbNewLine & "THEN" & vbNewLine & "RETURN return_value;" & vbNewLine & "ELSE" & vbNewLine & "RETURN NULL;" & vbNewLine & "END IF;" & vbNewLine & "END;" & vbNewLine & "/"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("return_value", OracleDbType.Varchar2, 100)
cmd.Parameters("return_value").Direction = ParameterDirection.Output
cmd.Connection = conn
cmd.ExecuteScalar()
Label1.Text = cmd.Parameters("return_value").Value
conn.Dispose()
End Sub
I am getting error at cmd.ExecuteScalar()
with ORA-00922: missing or invalid option

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??

Naming a access Table From textbox's text

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)

'Addcustomer' not a member of 'sql'. visual basic

I am trying to insert 3 textbox values into my database using a visual basic form, I have previously done this on another form and it worked correctly so I copied the code and changed the names to suit but I am getting the falling error: 'Addcustomer' not a member of 'sql'.
Any help will be appreciated.
Here is my code used on the form, this is where the error is underlined in blue:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Sql.Addcustomer(addcustomerfname.Text, addcustomersname.Text, addcustomeremail.Text)
MsgBox("Customer Added")
addeditmembership.Show()
Me.Hide()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Okay I am very new to VB and am only doing it for a uni assignment so have just been following lecturer instructions.
Here is my full code for the control file (this includes the working insert and the faulty one), I know its probably some stupid error but it's got me stumped.
Public Class SQLControl
Public SQLCon As New SqlConnection With {.ConnectionString = "Data Source=WADE\SQL2012;Initial Catalog=master;Integrated Security=True;"}
Public SQLCmd As SqlCommand
Public SQLDA As SqlDataAdapter
Public SQLDS As DataSet
Public Function HasConnection() As Boolean
Try
SQLCon.Open()
SQLCon.Close()
Return True
Catch ex As Exception
MsgBox(ex.Message)
End Try
Return False
End Function
Public Sub RunQuery(Query As String)
Try
SQLCon.Open()
' CREATE COMMAND
SQLCmd = New SqlCommand(Query, SQLCon)
'Fill Dataset
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDS = New DataSet
SQLDA.Fill(SQLDS)
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message )
'Close connection
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
End Sub
Public Sub Addmember(member_fname As String, member_sname As String, member_gender As String, member_dob As String,
member_address As String, member_postcode As String, member_email As String, member_contact_number As String,
member_registration As String, member_discount_rate As Integer)
Try
Dim strinsert As String = "INSERT INTO members (member_fname,member_sname,member_gender,member_dob,member_address,member_postcode,member_email,member_contact_number,member_registration,member_discount_rate " & _
")VALUES(" & _
"'" & member_fname & "'," & _
"'" & member_sname & "'," & _
"'" & member_gender & "'," & _
"'" & member_dob & "'," & _
"'" & member_address & "'," & _
"'" & member_postcode & "'," & _
"'" & member_email & "'," & _
"'" & member_contact_number & "'," & _
"'" & member_registration & "'," & _
"'" & member_discount_rate & "')"
SQLCon.Open()
SQLCmd = New SqlCommand(strinsert, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Public Sub Addcustomer(addcustomerfname As String, addcustomersname As String, addcustomeremail As String)
Try
Dim customerinsert As String = "INSERT INTO customers (customer_fname,customer_sname,customer_email " & _
")VALUES(" & _
"'" & addcustomerfname & "'," & _
"'" & addcustomersname & "'," & _
"'" & addcustomeremail & "')"
SQLCon.Open()
SQLCmd = New SqlCommand(customerinsert, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Your code contains several issues, the worst being proneness to SQL injection attacks, but solving this is a different story. (One easy thing to do is to parameterize your query. See this StackOverflow question for an example of how to do this.)
Regarding your immediate issue: Addcustomer is declared inside a class SQLControl. You're calling Sql.Addcustomer, which implies that the form class containing Button1_Click should have a field or property called Sql having type SQLControl. If that is not the case, then you must declare and initialize a field / property Sql As SQLControl.

How to populate faster in datagridview in vb.net

This is my code for populating the datagridview:
Public Sub generate_list_ftMK(ByVal clbBranch As CheckedListBox, ByVal dtpSDate As DateTimePicker, ByVal dtpEDate As DateTimePicker, ByVal dvList As DataGridView)
Dim ds As DataSet = New DataSet()
Dim da As MySqlDataAdapter
Dim strQ As String = String.Empty
Dim strQ1 As String = String.Empty
Dim colItemCode As String = String.Empty
Dim colReg_Pri As String = String.Empty
Dim colXL_Pri As String = String.Empty
Dim colDel_Date As String = String.Empty
Dim colLabel As String = String.Empty
Dim colDays As String = String.Empty
Dim PCT As String = String.Empty
Try
If con.State = ConnectionState.Open Then con.Close()
con.Open()
'clear the dataset
ds.Tables.Clear()
'loop for all branches
For i = 0 To clbBranch.CheckedItems.Count - 1
Application.DoEvents()
'get the Branch Code
chkBranch = clbBranch.CheckedItems(i).ToString
'select item code and price where JO_TYPE is JO
strQ = "select " & _
"CONCAT(a.STYLE_CODE, '-', LPAD((a.JO_NO), 4, '0'), '-', d.LINE_NO) as Item_Code, " & _
"DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d') as DEL_DATE, " & _
"d.REG_PRI as Reg_Price, " & _
"d.XL_PRI as XL_Price, " & _
"a.LABEL_CODE, " & _
"a.STYLE_CODE, " & _
"LPAD((a.JO_NO), 4, '0')," & _
"d.LINE_NO, " & _
"DATEDIFF('" & Format(Date.Now, "yyyy-MM-dd") & "',DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d')) as Days " & _
"from " & _
"jo_hdr as a " & _
"inner join " & _
"branch as b ON a.BRNCH_CODE = b.BRNCH_CODE " & _
"inner join " & _
"dr_hdr as c ON c.TRAN_REF = a.TRAN_NO " & _
"inner join " & _
"dr_det as d ON d.DR_NO = c.DR_NO " & _
"where " & _
"c.DEL_DATE BETWEEN '" & dtpSDate.Text & "' AND '" & dtpEDate.Text & "' " & _
"and a.LABEL_CODE = '" & FtMK_Code & "' " & _
"and a.BRNCH_CODE = '" & chkBranch & "' " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.REG_PRI) - 1,2) = 75 " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.XL_PRI) - 1,2) = 75 "
cmd = New MySqlCommand(strQ, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "tblJO")
For r = 0 To ds.Tables("tblJO").Rows.Count - 1
Application.DoEvents()
colItemCode = ds.Tables("tblJO").Rows(r)(0).ToString
colDel_Date = ds.Tables("tblJO").Rows(r)(1).ToString
colReg_pri = ds.Tables("tblJO").Rows(r)(2).ToString
colXL_pri = ds.Tables("tblJO").Rows(r)(3).ToString
colLabel = ds.Tables("tblJO").Rows(r)(4).ToString
sumStyle = ds.Tables("tblJO").Rows(r)(5).ToString
sumJO = ds.Tables("tblJO").Rows(r)(6).ToString
sumNo = ds.Tables("tblJO").Rows(r)(7).ToString
colDays = ds.Tables("tblJO").Rows(r)(8).ToString
'for the number to decimal
colReg_pri = FormatNumber(colReg_pri, 2)
colXL_pri = FormatNumber(colXL_pri, 2)
'get the total quantity and the branch quantity
get_TotalQty_and_BranchQty()
'if the branch quantity is zero
If branchQty = 0 Then
PCT = "N\A"
Else
'compute the percent sold
PCT = totalQty
End If
dvList.Rows.Add(False, colItemCode, PCT, colDel_Date, Format(Date.Now, "yyyy-MM-dd"), colDays, _
colReg_Pri, colXL_Pri, colLabel, "JO", dtpSDate.Text, dtpEDate.Text, _
clbBranch.CheckedItems(i).ToString, mkType)
Next
Next
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
I have use indexes in my tables, and also add application.doevents. Is there anything I could do to make the populating in the datagridview faster with this code? I'm trying to search about making the datagridview doublebuffered because I read it online that I will make the datagridview faster but I have no idea how to use it.
Any help will be appreciated, Thank you.
Your issue is using
Application.DoEvents
I'm not going to get into the details of why this is bad practice, try using a Background Worker instead.