My question is my code has problem or not to insert into database. Why I cannot insert it?
I think the data has saved but it not show in database. Please help me see it, thank you.
Dim con As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\HTPdatabase.mdf;Integrated Security=True"
cmd.CommandText = "INSERT INTO Customer (Username,Password,Name,IC,Address,Email,Carpark,topup)VALUES(#Username,#password,#Name,#IC,#address,#Email,#Carpark,#topup)"
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#password", PasswordTextBox.Text)
cmd.Parameters.AddWithValue("#Name", DBNull.Value)
cmd.Parameters.AddWithValue("#IC", DBNull.Value)
cmd.Parameters.AddWithValue("#address", DBNull.Value)
cmd.Parameters.AddWithValue("#Email", DBNull.Value)
cmd.Parameters.AddWithValue("#Carpark", DBNull.Value)
cmd.Parameters.AddWithValue("#topup", DBNull.Value)
MsgBox("Successfully register!Please remind customer to update own profile,Thank you !")
cmd.ExecuteNonQuery()
con.Close()
End Sub
As per your code it looks ok but
Place
MsgBox("Successfully register!Please remind customer to update own profile,Thank you !")
below
cmd.ExecuteNonQuery()
because during cmd.ExecuteNonQuery() code may fail and exception may raise.
Related
I am trying to create a user and insert the data into a MS Access database, but I get an error:
The connectionString property has not been initialized
whenever I click on the button.
I have tried all possible codes on Connection string but the challenge still persist.
Try
Dim sqlconn As New OleDb.OleDbConnection
Dim sqlquery As New OleDb.OleDbCommand
Dim connString As String
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"
sqlquery.Connection = sqlconn
con = New OleDbConnection(conString)
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sql, con)
sqlquery.CommandText = "INSERT INTO member(mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress, #txtPhone, #txtPhone, #)txtAccNo"
sqlquery.Parameters.AddWithValue("New ID", txtNewID.ToString)
sqlquery.Parameters.AddWithValue("Name", txtName.ToString)
sqlquery.Parameters.AddWithValue("Gender", txtGender.ToString)
sqlquery.Parameters.AddWithValue("Address", txtAddress.ToString)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataTable
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "con")
Return
sqlquery.ExecuteNonQuery()
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
That code really is a mess. It should be reduced to this and that will fix your issue:
Try
Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"),
command As New OleDbCommand("INSERT INTO member (mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#mmbr_id, #name, #gender, #address, #phone, #join_date, #acc_no)", connection)
With command.Parameters
.AddWithValue("#mmbr_id", txtNewID.Text)
.AddWithValue("#name", txtName.Text)
.AddWithValue("#gender", txtGender.Text)
.AddWithValue("#address", txtAddress.Text)
'Set other parameters here.
End With
connection.Open()
command.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Ideally, you would be using Add rather than AddWithValue too, but that's another conversation.
Here is simple code for what you mostly asked for, in addition to the whole open source on this link:
enter link description here
Here is the tested code:
Private Sub BtnAddNewRec_Click(sender As Object, e As EventArgs) Handles BtnAddNewRec.Click
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\db1.mdb"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Tbl1 (mmbr_id, name, gender, address) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress)"
cmd.Parameters.AddWithValue("#txtNewID", txtNewID.Text)
cmd.Parameters.AddWithValue("#txtName", txtName.Text)
cmd.Parameters.AddWithValue("#txtGender", txtGender.Text)
cmd.Parameters.AddWithValue("#txtAddress", txtAddress.Text)
cmd.ExecuteNonQuery()
MsgBox("Record Added Successfully!")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
I hope this helps:
The trouble here is that you have 2 commands in your code, namely cmd and sqlquery. You define sqlquery at the beginning of the code, then initialize cmd with the connection and a SQL variable that I cannot determine the source of.
What you need to do is redo this part and get remove the extra references that seem to be the source of the problem. Consider the following...
Try
Dim conString As String
Dim text = "INSERT INTO member(mmbr_id, name, gender, address, phone, join_date, acc_no) VALUES (#txtNewID, #txtName, #txtGender, #txtAddress, #txtPhone, #txtPhone, #)txtAccNo"
conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PavilionDB.mdb"
Using sqlCon = New OleDbConnection(conString), sqlCmd = New OleDbCommand(text, sqlCon)
With sqlCmd.Parameters
.AddWithValue("New ID", 234234)
.AddWithValue("Name", "Fabulous")
.AddWithValue("Gender", "Male")
.AddWithValue("Address", "127.0.0.1")
End With
sqlCon.Open()
sqlCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
I couldn't tell whether txtNewID and the other similarly named variables are text boxes or not. If they are text boxes, you need the .Text property which gets the content in a string. You'll need to replace the literals I used in my test environment to get to it.
Ensure everything, including your connection string and query are correct for this to run smoothly. In your current case, you are getting the connection string related error because you are attempting to execute the query on a connection you didn't associate with the connection.
I'm looking to add a row with an autonumeric value using SQL.
I'm using Studio VB 2010. I have a very simple table with 2 fields:
ID Autonumeric
Model Text field.
constr = "INSERT INTO procedures VALUES('" & txtFName.Text & "')"
cmd = New OleDbCommand(constr, cn)
cn.Open()
Me.i = cmd.ExecuteNonQuery
A message says a parameter is missing,
so my question is...
How can I add in the SQL command this automatic value? (ID)
Should I get the last ID number and +1 ?? I think there's gotta be a simple way to do it.
Thank you.
Update #1
I am now trying parameterized queries as suggested...
I found this example,
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.Add("#a1", OleDbType.Integer).Value = 0
.Add("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
But still, I'm geting a Syntaxis error.
Any thoughts?
Thanks to you all.
UPDATE #2
This code seems to work if I give the next ID number, but again, how can I do it automatically?
Dim cmdText As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(cmdText, con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#a1", OleDbType.Integer).Value = 3
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
cmd.ExecuteNonQuery()
con.Close()
Any comments? Thanks again.
UPDATE #3 This Code gives me Syntaxis Error
I just put my only one column to update, the second one is the autonumber column, as I was told to try.
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO procedures (procedure) VALUES ('Model')"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
Try
Con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
UPDATE #4 - SOLUTION
I'm putting this code in here in case someone finds it useful.
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;"
dbSource = "Data Source = c:\gastrica\dabase.accdb"
Con.ConnectionString = dbProvider & dbSource
Dim Con As OleDbConnection = New OleDbConnection(dbProvider & dbSource)
Dim SQL_command As String = "INSERT INTO [procedures] ([procedure]) VALUES (?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#procedure", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
Dim varProcedure As String = cmd.Parameters("#procedure").Value.ToString()
MessageBox.Show("Record inserted successfully. Procedure = " & varProcedure)
Catch ex As Exception
Throw ex
Finally
Con.Close()
End Try
Thanks all for your comments and help.
You need to specify the columns:
INSERT INTO procedures (columnname, columnname2) VALUES ('test', 'test');
Here is a sql fiddle showing an example:
http://sqlfiddle.com/#!9/3cf706/1
Try this one:
constr = "INSERT INTO procedures (ID, Model) VALUES (0,'" & txtFName.Text & "')"
'or (not sure)
constr = "INSERT INTO procedures (Model) VALUES ('" & txtFName.Text & "')"
When use 0 as value, in autonumeric fields SQL insert the next number
Thanks for your answers.
I couldnĀ“t do it, it gives me errors. So I end up with a single variable reaching the next Auto Value. Using a simple SQL command.
And then, everything runs good.
vNextAuto = GetDB_IntValue("SELECT TOP 1 * FROM procedures ORDER BY ID DESC", "ID") + 1
Dim SQL_command As String = "INSERT INTO procedures VALUES (?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SQL_command, Con)
cmd.CommandType = CommandType.Text
With cmd.Parameters
.AddWithValue("#id", OleDbType.Integer).Value = vNextAuto
.AddWithValue("#a2", OleDbType.VarChar).Value = txtFName.Text
End With
Try
Con.Open()
cmd.ExecuteNonQuery()
'Dim id As String = cmd.Parameters("#id").Value.ToString()
'MessageBox.Show("Record inserted successfully. ID = " & id)
Catch ex As Exception
Throw ex
Finally
Con.Close()
Con.Dispose()
End Try
I want to Insert 2 different data in 2 different table of ms-access.
And it shows this error.
I have a code like this:
try
dim sql1,sql2 as string
sql1 = "INSERT INTO table1(something)VALUES(something)"
cmd = new oledbcommand(sql1, connection)
cmd.executenoquery()
sql2 = "INSERT INTO table2(something)VALUES(something)"
cmd2 = new oledbcommand(sql2, connection)
cmd2.executenoquery()
catch ex as exception
msgbox(ex.tostring())
(where these cmd1,cmd2 are defined in controlModule.)
so,what should I do ?
Any help is appreciated. Thank You
I think closing the connection fixes the issue, best by using the Using-statement:
try
Using con As OleDbConnection = GetConnection() ' or New OlebConnection(...)
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table1(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Using con As OleDbConnection = GetConnection()
Using cmd = con.CreateCommand()
cmd.CommandText = "INSERT INTO table2(something)VALUES(#something)"
cmd.Parameters.AddWithValue("#something", something)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
msgbox(ex.tostring())
End Try
This is a concurrency issue. Because some other part of your code or MS Access itself accesses the database at the same time.
The fact is that you're not closing the connection after it's use. So the 2nd call should fail with that exception. Instead, you should wrap your disposables - e.g. the OleDbConnection, commands, etc. - in a using statement. That way, the connection will be closed, even if an exception occur:
Using con As New OleDbConnection, cmd1 As OleDbCommand = con.CreateCommand, cmd2 As OleDbCommand = con.CreateCommand()
cmd1.CommandText = "INSERT INTO table1(something)VALUES(something)"
cmd1.ExecuteNonQuery()
cmd2.CommandText = "INSERT INTO table2(something)VALUES(something)"
cmd2.ExecuteNonQuery()
End Using
con = New OleDb.OleDbConnection(Con_String)
cmd = New OleDb.OleDbCommand("delete from Accessed_DB where pathofdb =#pathofdb", con)
con.Open()
cmd.Parameters.RemoveAt("#pathofdb")
cmd.ExecuteNonQuery()
MsgBox("Record Deleted")
con.Close()
I am using above code to delete data but it not get successful. why?
cmd.Parameters.RemoveAt("#pathofdb")
should probably be
cmd.Parameters.AddWithValue("#pathofdb", "some path")
Having said that I don't think OLEDB supports named arguments in the SQL syntax so I think your command should be:
cmd = New OleDb.OleDbCommand("delete from Accessed_DB where pathofdb =?", con)
As you can probably very soon see, I am a complete newbie at VB.NET, and I am having some trouble getting output from a stored procedure in SQL Server 2005.
This is the code I use
Dim con As New SqlConnection
Dim cmd As New SqlCommand("esp_getDates", con)
Dim par As New SqlParameter("#PlaceID", SqlDbType.Int, 3906)
con.ConnectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test"
con.Open()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters("#PlaceID").Direction = ParameterDirection.Output
cmd.ExecuteNonQuery()
con.Close()
I get the error;
An SqlParameter with ParameterName
'#PlaceID' is not contained by this
SqlParameterCollection.
Does anyone see what I'm doing wrong / have any suggestions how I can fix it? Code examples would be very helpful and any help is much appreciated.
You aren't actually adding the parameter to the cmd.Parameters collection:
cmd.Parameters.Add(par)
Alternatively, just add the parameter without instantiating the Parameter object explicitly:
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
Also, I'd follow the principle of using a variable as close to the declaration as possible and reorganize things this way:
Dim con As New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test")
con.Open()
Dim cmd As New SqlCommand("esp_getDates", con)
Try
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#PlaceID", SqlDbType.Int)
cmd.Parameters("#PlaceID").Value = 3906
cmd.ExecuteNonQuery()
Finally
If cmd IsNot Nothing Then cmd.Dispose()
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close()
End Try