Please help i am a newbie on oracle database i am used on using mysql and i really don't have any idea how can i debug my code. Here is my code.
Imports System.Diagnostics
Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types
Public Class mainMenu
Dim conn As New OracleConnection
Private cmd As OracleCommand
Private da As OracleDataAdapter
Private cb As OracleCommandBuilder
Private ds As DataSet
Private Sub mainMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler txtProductName.TextChanged, AddressOf ValidateInputs
AddHandler txtQty.TextChanged, AddressOf ValidateInputs
AddHandler txtPrice.TextChanged, AddressOf ValidateInputs
conn.ConnectionString = "User Id=antonina" & _
";Password=antonina" & _
";Data Source=xe"
Try
conn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
Finally
conn.Dispose()
End Try
End Sub
Private Sub ValidateInputs(ByVal Sender As Object, ByVal e As EventArgs)
Button1.Enabled = Not (txtProductName.Text = String.Empty OrElse txtQty.Text = String.Empty OrElse txtPrice.Text = String.Empty)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim productName As String
Dim qty As Integer
Dim price As Integer
Dim cat As String
productName = txtProductName.Text
qty = Integer.Parse(txtQty.Text)
price = Integer.Parse(txtPrice.Text)
cat = cmbCat.Text
conn = New OracleConnection("User Id=antonina;Password=antonina;Data Source=xe")
da = New OracleDataAdapter()
Try
da.InsertCommand = New OracleCommand("INSERT INTO INVENTORY(INVENTORY_PRODUCTNAME,INVENTORY_CAT,INVENTORY_QTY,INVENTORY_PRICE) VALUES ('" & productName & "'," & qty & "," & price & ",'" & cat & "')", conn)
Debug.WriteLine("Success")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
When i click my add button it says object reference not set to an instance of an object. I know i might just have a stupid syntax error. Please help me.
I am sure that all my variables have a value. also i am using oracle 10g
I have never seen that somebody uses a OracleDataAdapter in order to insert anything to database, usually OracleDataAdapter is used to retrieve data from database, i.e. a SELECT ... command or a function call which gets a RefCursor.
Perhaps InsertCommand, resp. UpdateCommand and DeleteCommand are used to modify data of OracleDataAdapter after it has been filled from your database - I do not know, I never used it. These command are called with method OracleDataAdapter.Update(da)
Anyway, usually you would do it like this:
Dim cmd As OracleCommand
cmd = New OracleCommand("INSERT INTO INVENTORY (INVENTORY_PRODUCTNAME,INVENTORY_QTY,INVENTORY_PRICE,INVENTORY_CAT) VALUES (:productName, :qty, :price, :cat)", conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("productName", OracleDbType.Varchar2, ParameterDirection.Input).Value = productName
cmd.Parameters.Add("qty", OracleDbType.Int32, ParameterDirection.Input).Value = qty
cmd.Parameters.Add("price", OracleDbType.Int32, ParameterDirection.Input).Value = price
cmd.Parameters.Add("cat", OracleDbType.Varchar2, ParameterDirection.Input).Value = cat
cmd.ExecuteNonQuery()
Note the order of columns, see your code:
INVENTORY_PRODUCTNAME, INVENTORY_CAT, INVENTORY_QTY, INVENTORY_PRICE
('" & productName & "'," & qty & "," & price & ",'" & cat & "')"
I assume da is for DataAdapter. You need first instantiate your dataadapter by call its constructor.
conn = new OracleConnection(yourConnectionString)
da = New OracleDataAdapter()
da.InsertCommand = New OracleCommand("INSERT INTO INVENTORY(INVENTORY_PRODUCTNAME,INVENTORY_CAT,INVENTORY_QTY,INVENTORY_PRICE) VALUES ('" & productName & "'," & qty & "," & price & ",'" & cat & "')", conn)
also, you missing '()' after VALUES statement in sql syntax.
Other things may help is you can move your parsing statement into try-catch element to avoid error.
hope this help.
Related
Code :
Private m_cn As New SqlConnection
Private m_DA As SqlDataAdapter
Private m_CB As SqlCommandBuilder
Private m_DataTable As New DataTable
Private m_intRowPosition As Integer = 0
Private Sub InsertDatabaseItem_Load(sender As Object, e As EventArgs) Handles MyBase.Load
m_cn.ConnectionString = "Data Source=My-PC\SQLSERVEREXPRESS;Initial Catalog=ConvienienceProducts;Integrated Security=True"
m_cn.Open()
m_DA = New SqlDataAdapter("Select * From ProductIndex", m_cn)
m_CB = New SqlCommandBuilder(m_DA)
End Sub
Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
txtID.Text & "," &
txtName.Text & "," &
txtPrice.Text & "," &
txtDesc.Text & ")"), m_cn)
cmd.ExecuteNonQuery()
MsgBox("Success....", MsgBoxStyle.Information, "SUCCESS")
Me.Hide()
txtID.Clear()
txtName.Clear()
txtPrice.Clear()
txtDesc.Clear()
m_cn.Close()
m_cn.Dispose()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Hide()
End Sub
This is the error message :
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ','.
You code should be using parameters. Try this:
Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES(" &
"#ID," &
"#Name," &
"#Price," &
"#Desc)"), m_cn)
cmd.Parameters.Add("#ID", SqlDbType.Char)
cmd.Parameters("#ID").Value = txtID.Text
cmd.Parameters.Add("#Name", SqlDbType.Char)
cmd.Parameters("#Name").Value = txtName.Text
cmd.Parameters.Add("#Price", SqlDbType.Char)
cmd.Parameters("#Price").Value = txtPrice.Text
cmd.Parameters.Add("#Desc", SqlDbType.Char)
cmd.Parameters("#Desc").Value = txtDesc.Text
The types are probably wrong (especially Price, and probably ID), but as you know what they are, and I don't, you can easily correct them.
You need to wrap your string values in single quotes
Dim cmd As New SqlCommand(("INSERT INTO ProductIndex VALUES('" & txtID.Text & "',
Hard to see but there is a single quote just before and after the double quotes surrounding your variables.
I have answered your particular question but you should be using parameters
Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then
I am a new user to VB.net ( of 2 weeks ) and coming from a php background, am finding it tough going. I have created a small form that should insert some data into an access mdb database. However, I keep getting an error of:
System.Data.OleDb.OleDbException
I have outlined in my pasted code where this error is occurring and would be grateful if someone could point out where I have gone wrong. many thanks.
Imports System.Data.OleDb
Public Class frmMain
Dim strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\domain\storage1.mdb"
Dim cnnOLEDB As New OleDbConnection(strConnectionString)
Dim cmdOLEDB As New OleDbCommand
Dim cmdInsert As New OleDbCommand
Dim cmdUpdate As New OleDbCommand
Dim cmdDelete As New OleDbCommand
Dim cmd As OleDbCommand
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
Dim InsertQuery As String
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cnnOLEDB.Open()
Dim cmd As OleDbCommand = New OleDbCommand(InsertQuery, cnnOLEDB)
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
cmd.ExecuteNonQuery() <--- ERROR
cnnOLEDB.Close()
MessageBox.Show("Insert complete.")
End Sub
End Class
The problem is here:
InsertQuery = "INSERT INTO Details (first,last,age) VALUES ('" & first & "','" & last & "','" & age & "')"
cmd.Parameters.AddWithValue("first", txtFirstName.Text)
cmd.Parameters.AddWithValue("last", txtLastName.Text)
cmd.Parameters.AddWithValue("age", txtAge.Text)
Try this:
InsertQuery = "INSERT INTO Details (first,last,age) VALUES (#first, #last, #age)"
Then for the Parameters:
cmd.Parameters.AddWithValue("#first", txtFirstName.Text)
cmd.Parameters.AddWithValue("#last", txtLastName.Text)
cmd.Parameters.AddWithValue("#age", txtAge.Text)
You can then remove these lines as you don't need them:
Dim first, last As String
Dim age As Integer
first = txtFirstName.Text
last = txtLastName.Text
age = txtAge.Text
First and Last are reserved words for Jet 4.0. They should not be used as column names. Access itself will let you get away with it, SQL code is a little less forgiving. If you can't avoid using those words, try putting them in square brackets [first] when addressing them. For more information on reserved words, see http://support.microsoft.com/kb/248738.
I have just started learning VB.net for several weeks. i want to make a form and send data from a text box to a specific cell in ms access database (*.accdb) file. but the code i have writen gives the following error:
Syntax error in UPDATE statement.
i have checked several books and spent hours on internet, but no answer!
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim cnn1 As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
E:\Ebook\hararat\GUI\Heat Exchanger Designer\heat.accdb"
con.Open()
sql = "SELECT * FROM flow1"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "flow1")
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("flow1").Rows(1).Item(1) = "name"
da.Update(ds, "flow1")
con.Close()
You need to use the .QuotePrefix and .QuoteSuffix properties of the OleDbCommandBuilder to wrap table and field names in square brackets. That is, instead of just
Dim cb As New OleDb.OleDbCommandBuilder(da)
you need to do
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will generate an UPDATE statement of the form
UPDATE [TableName] SET [ColumnName]= ...
which is necessary if the table name or any of the field names happen to be reserved words in Access SQL.
Try this one
dim sqlupdate as string = "UPDATE tablename SET column_name = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this:
UPDATE tablename SET [Username] = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
my codes goes like this:
Open_Con()
Dim sqlUpdate As String
Dim sqlUpdatePass As DialogResult
sqlUpdate = "UPDATE tblAccounts SET [Password] = '" & txtRPassword.Text & "' WHERE [Username] = '" & txtUsername.Text & "'"
sqlCmd = New OleDbCommand(sqlUpdate, sqlCon)
Try
sqlUpdatePass = MessageBox.Show("Are you sure to save this changes?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If sqlUpdatePass = vbYes Then
sqlCmd.ExecuteNonQuery()
MsgBox("Changes are now saved", MsgBoxStyle.Information, "New password has been set.")
Call ClearAll()
Me.Hide()
Else
Exit Sub
End If
Catch ex As Exception
MsgBox("Could not perform this task because " & ex.Message, MsgBoxStyle.Exclamation, "Error")
End Try
sqlCmd = Nothing
sqlCon.Close()
hope this things mention above codes helps your problem. have a nice day and happy coding :)
dim sqlupdate as string="UPDATE [tablename] SET [column_name] = '"& textname.text &"' WHERE [column_name] = '"& textname.text &"';"
By enclose attributes with square brackets, it appears to work I have tried it, it works
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database2DataSet.identitas' table. You can move, or remove it, as needed.
Me.IdentitasTableAdapter.Fill(Me.Database2DataSet.identitas)
End Sub
Public Sub clean()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
End Sub
Public Sub read()
Call openconn()
str = "select * from identitas"
dtadapter = New OleDbDataAdapter(str, con)
Dim dg As New DataTable
dg.Clear()
dtadapter.Fill(dg)
dgv.DataSource = dg
End Sub
Public Sub create()
Call openconn()
str = "insert into identitas values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "') "
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data lebet")
read()
clean()
End Sub
Public Sub update()
Call openconn()
str = "UPDATE identitas SET [Nama] = '" & TextBox2.Text & "',[Alamat] = '" & TextBox3.Text & "', [No] = '" & TextBox4.Text & "' where [NIK] = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data ter ubah")
clean()
read()
End Sub
Public Sub delete()
Call openconn()
str = "delete from identitas where NIK = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
clean()
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub btnc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnc.Click
create()
End Sub
Private Sub btnr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnr.Click
read()
End Sub
Private Sub btnclean_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclean.Click
clean()
End Sub
Private Sub btnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnd.Click
Dim pesan As String = MsgBox("yakin mau hapus = " & TextBox1.Text & "?", MsgBoxStyle.YesNo)
If pesan = vbYes Then
delete()
End If
read()
End Sub
Private Sub btnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnu.Click
update()
End Sub
End Class
I had same problem, this helped.
"Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this: "
I renamed the columns in Access (e.g Password1,Username1) as the same words password, username might be reserved in vb.net. Thanks for this response.
Private Sub lvUnavailableProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvUnavailableProducts.SelectedIndexChanged
Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM Product_Suppliers WHERE ProductCode = '" & lvUnavailableProducts.SelectedItems(0).SubItems(0).Text & "'", conn)
conn.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
If sdr.Read = True Then
Fill("SELECT DISTINCT SupplierCode, SupplierName FROM Product_Suppliers WHERE ProductCode ='" & lvUnavailableProducts.SelectedItems(0).SubItems(0).Text & "'", lvProductSupplier)
conn.Close()
Else
MsgBox("No added Supplier Yet, Please add a supplier")
lvProductSupplier.Items.Clear()
conn.Close()
End If
End Sub
I Am encountering an error when selected data on LvUnavailableProducts was changed
Please Help Thank you :D
Try changing .SelectedItems(0) into .FocusedItem
lvUnavailableProducts.FocusedItem.SubItems(0).Text