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.
Related
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
pls help solve me this question.. im very new to this
i can't add new employee to the table employee.. whenever i try to add it shows syntax error insert into statement
Public Class AddNewEmployee
Dim dr As OleDbDataReader
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim conn As New OleDbConnection(My.Settings.rayshadatabaseConnectionString)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn.Open()
Try
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
cmd = New OleDbCommand(str, conn)
Dim i As Integer = cmd.ExecuteNonQuery()
If i > 0 Then
MessageBox.Show("Record Succesfully added.", "Process Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Adding failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
cmd.Dispose()
End Try
frmEmployee.loadR()
Me.Close()
End Sub
End Class
Replace this,
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
with this,
Dim str As String = "INSERT INTO employee" _
& "([Employee Name], [IC Number], [HP Number], [Address])" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
Thanks
Manoj
I'm running Visual studio and whenever I run my application it says "Incorrect syntax error near '(the email i enter appears here)'". I hope you can spot the mistake.
Within SQL server, my email column is called 'email'
Within Visual studio, the name of the input field for my email is called 'textEmail'
Public Sub AddCustomer(Firstname As String, Surname As String, Contactnum As String, Email As String)
Try
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "'"
MsgBox(strInsert)
SQLCon.Open()
SQLcmd = New SqlCommand(strInsert, SQLCon)
SQLcmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Code within form:
Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
'QUERY FOR CUSTOMER
SQL.RunQuery("SELECT * FROM customers WHERE customers.email = '" & txtEmail.Text & "' ")
If SQL.SQLDS.Tables(0).Rows.Count > 0 Then
MsgBox("This Email alredy exists!")
Exit Sub
Else
CreateCustomer()
End If
End Sub
Public Sub CreateCustomer()
' ADD CUSTOMER TO DATABASE
SQL.AddCustomer(txtFirst.Text, txtSur.Text, txtNum.Text, txtEmail.Text)
End Sub
End Class
Thanks for your time.
You are missing closing bracket
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "')"
Ok, I have looked at a bazillion multi-threading examples; all show cute little counters on a form, while you can still access the form, using backgroundworker, or threadpools. I got it. What I don't get is to apply this into a real world application.
Here's my application, and I don't have a clue on how to multi-thread this;
Through a 3rd party ActiveX API I read in records to a SQL table at high rate; several million records in 8hours a day.
While the streaming of the records occurs, I need to go over the records, do some calculations and apply filters, and represent the results in realtime. (filters it down to around a 100 records/day)
I guess you see already where I'm going with this;
If I do the calculations/filters on the fly when records are streaming in; it causes the streaming to delay and I loose the connection, So I need to multi-thread the two tasks.
the streaming into SQL table is done as follows: (AxTDAAPIComm is the ActiveX)
On Form1 :
Private Sub SubscrBTN_Click(sender As Object, e As EventArgs) Handles SubscrBTN.Click
AxTDAAPIComm1.Subscribe(StreamOL, tdaactx.TxTDASubTypes.TDAPI_SUB_L1)
End Sub
Private Sub AxTDAAPIComm1_OnL1Quote(sender As Object, e As Axtdaactx.ITDAAPICommEvents_OnL1QuoteEvent) Handles AxTDAAPIComm1.OnL1Quote
SQL.AddStream(e.quote.Symbol, e.quote.Bid, e.quote.Ask, e.quote.Last, e.quote.PrevClose, e.quote.Volume, e.quote.TradeTime, e.quote.QuoteTime, e.quote.TradeDate, e.quote.QuoteDate, e.quote.Volatility, e.quote.OpenInterest, e.quote.UnderlyingSymbol, e.quote.CallPut, e.quote.LastSize, e.quote.MH_LastSize, e.quote.MH_IsQuote, e.quote.MH_IsTrade)
End Sub
End Class
clicking on the button, invokes the AxTDAAPIComm1_OnL1Quote sub, which streams back records.
Then in my SQL Class I send it off to my SQL table:
Public Sub AddStream(Symbol As String, Bid As Single, Ask As Single, Last As Single, PrevClose As Single, Volume As Integer, TradeTime As Integer, QuoteTime As Integer, TradeDate As Integer, Quotedate As Integer, Volatility As Single, OpenInterest As Integer, UnderlyingSymbol As String, CallPut As String, LastSize As Integer, MH_LastSize As Integer, MH_IsQuote As Boolean, MH_IsTrade As Boolean)
Try
Dim TradeAmount As Single = 0
Dim Trade As String = ""
TradeAmount = LastSize * Last * 100
Select Case Last
Case Is = Ask
Trade = "Ask"
Case Is > Ask
Trade = "Above Ask"
Case Is = Bid
Trade = "Bid"
Case Is < Bid
Trade = "Below Bid"
Case Else
Trade = "Mid"
End Select
Dim strStream As String = "INSERT INTO OptionStream (Symbol,Bid,Ask,Last,PrevClose,Volume,TradeTime,QuoteTime,TradeDate,QuoteDate,Volatility,OpenInterest,UnderlyingSymbol,CallPut,TradeAmount,Trade,LastSize,MH_LastSize,MH_IsQuote,MH_IsTrade) " & _
"VALUES (" & _
"'" & Symbol & "'," & _
"'" & Bid & "'," & _
"'" & Ask & "'," & _
"'" & Last & "'," & _
"'" & PrevClose & "'," & _
"'" & Volume & "'," & _
"'" & TradeTime & "'," & _
"'" & QuoteTime & "'," & _
"'" & TradeDate & "'," & _
"'" & Quotedate & "'," & _
"'" & Volatility & "'," & _
"'" & OpenInterest & "'," & _
"'" & UnderlyingSymbol & "'," & _
"'" & CallPut & "'," & _
"'" & TradeAmount & "'," & _
"'" & Trade & "'," & _
"'" & LastSize & "'," & _
"'" & MH_LastSize & "'," & _
"'" & MH_IsQuote & "'," & _
"'" & MH_IsTrade & "') "
SQLCon.Open()
SQLCmd = New SqlCommand(strStream, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
On my Form I have created a text box, which I use to enter a SQL query statement, which I capture as follows:
Private Sub cmdQuery_Click(sender As Object, e As EventArgs) Handles cmdQuery.Click
If txtQuery.Text <> "" Then
If SQL.HasConnection = True Then
SQL.RunQueryWL(txtQuery.Text)
If SQL.SQLDatasetWL.Tables.Count > 0 Then
DGVData.DataSource = SQL.SQLDatasetWL.Tables(0)
End If
End If
End If
End Sub
As you can see, it now goes of to the SQL class and runs the Query:
Public Function HasConnection() As Boolean
Try
SQLCon.Open()
SQLCon.Close()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
Public Sub RunQueryWL(Query As String)
Try
SQLCon.Open()
SQLCmd = New SqlCommand(Query, SQLCon)
SQLDA = New SqlDataAdapter(SQLCmd)
SQLDatasetWL = New DataSet
SQLDA.Fill(SQLDatasetWL)
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
If SQLCon.State = ConnectionState.Open Then
SQLCon.Close()
End If
End Try
End Sub
and the result is presented in a datagrid view on my form.
As you can imagine, querying against a couple million records takes a few seconds, therefore I want to put the AxTDAAPIComm1.Subscribe and AxTDAAPIComm1_OnL1Quote and the RunQueryWL Subs on different threads.
How do I do this?
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.