I keep getting a "Connection was not established" error. Though I thought, what with opening the Connection with sqlLink.Open and sqlCheck.connection = sqlLink, that this error wouldn't appear.
Imports System.Data.OleDb
Public Class StockAdd
Dim path = System.Windows.Forms.Application.StartupPath
Dim sqlLink As OleDbConnection
Private Sub StockAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sqlLink = New OleDbConnection
sqlLink.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\will\Documents\Computing\ComputingProjectDatabase.accdb';")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlCheck As New OleDbCommand
Dim oleRdr As OleDbDataReader
sqlLink.Open()
Try
Using sqlOrder As New OleDbCommand
sqlCheck.Connection = sqlLink
sqlCheck.CommandText = "SELECT count(*) FROM StockSystem WHERE [Stock ID] = #stockID"
sqlCheck.Parameters.AddWithValue("#stockID", TextBox5.Text)
oleRdr = sqlCheck.ExecuteReader()
If oleRdr.HasRows = True Then
oleRdr.Read()
If oleRdr.Item(0) = 0 Then
sqlOrder.CommandText = "INSERT INTO StockSystem ([Stock ID], [Stock Price], [Stock Size], [Stock Quantity], [Stock Category]) VALUES ('" & TextBox5.Text & "','" & TextBox7.Text & "','" & TextBox6.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "')"
sqlOrder.ExecuteNonQuery()
MsgBox("Stock Details Stored.")
Else
MsgBox("Please check you have entered the correct data.")
End If
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
sqlLink.Close()
Me.Close()
Stock.Show()
End Sub
End class
If my eyes don't fail me, you don't set the connection for the sqlOrder command. So it cannot execute your sql text.
Pay attention, you cannot use the sqlLink connection because it is used by the datareader. You need a new connection object (with the same connection string of course)
As a side note, your code is very vulnerable to Sql Injection. And probably could have serious problems if one or more of your TextBoxes contains a single quote char.
Always use a parameterized query as the one used for the COUNT() statement before
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
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.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim sqlquery As String = "INSERT INTO Table1(Customer Name,Address,Contact Number,Type Of Customer)VALUES('" & TextBox1.Text & "', '" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "')"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
End With
MsgBox("ONE RECORD SUCCESFULLY ADDED :)")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can somebody help me? It says that there is an error in INSERT INTO statement, i dont know why. Thanks for the help.
Try putting [] around column names that contain a space.
( [Customer Name], Address, [Contact Number], [Type Of Customer] )
It is important to enclose your field in [your field] when they have spaces in them, else it considers it as two fields and search for separator which there is none in this case.
hopes my answers helps a little.
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.
Hi heres the code it has no errors but when you check the database nothing is added
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Create_btn.Click
Call getConnect()
If New_Username.Text = "" And New_Password.Text = "" And New_Pass_Code.Text = "" Then
MsgBox("check the empty textbox or wrong Admin Password", MsgBoxStyle.Critical, "needed")
Else
con.Open()
sql = "INSERT into Accounts (Username, Password, Pass_Code) values('" _
& New_Username.Text & "','" _
& New_Password.Text & "' , '" _
& New_Pass_Code.Text & "')"
Dim sqlcomd As New SqlClient.SqlCommand
sqlcomd.CommandText = sql
sqlcomd.Connection = con
sql = sqlcomd.ExecuteNonQuery
MsgBox("data saved")
con.Close()
End If
try to check your connection string. the data might be saving to another database.