VB.Net Insert Into SQL Database - vb.net

I was hoping someone could explain this a bit better for me.
I have a visual studio project and created the database in the project: Project >> Add Item >> Service Database. I have a form with a textbox that I am trying to insert data into and I have looked up how to do this and there are things like SQLCommand or ExecuteNonQuery are not an option I have.
Since the database is associated with the project I don't know if I even need to do that part but I haven't seen anything to the contrary. I don't want to hard code in a server connection if I can avoid it because I am hoping this will become an application.
This is my code so far
Private Sub btnAddNewSpellSchool_Click(sender As Object, e As EventArgs) Handles btnAddNewSpellSchool.Click
Dim sqlCMD As String
Dim text As String
text = Me.txtAddSpellSchool.Text
sqlCMD = "INSERT INTO tblList_Spell_Config_SpellSchool (spellSchool) VALUES('" & text & "')"
End Sub
This is what I have been seeing
Dim DA As SqlDataAdapter = New SqlDataAdapter
Dim Parm As New SqlParameter
DA.InsertCommand = New SqlCommand("Insert Into tbl1(fld0, fld1, fld2) Values(#fld0, #fld1, #fld2)", conn)
Parm = DA.InsertCommand.Parameters.Add(New SqlParameter ("#fld0", NVarChar, 50, "fld0"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld1", SqlDbType.NVarChar, 50, "fld1"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld2", SqlDbType.NVarChar, 50, "fld2"))
DA.Update(dataset1, "tbl1")

Imports System.Data
Imports System.Data.SqlClient
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconn As SqlConnection
Dim mycmd As SqlCommand
Dim qry As String
qry = "Insert Into tblList_Spell_Config_SpellSchool (spellSchool) Values('Air')"
myconn = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jpac0\Dropbox\Dungeon and Dragons\DND_Application\DND_ExperienceBuilder\DND_ExperienceBuilder\DND_ExperienceBuilderDB.mdf;Integrated Security=True;Connect Timeout=30")
myconn.Open()
mycmd = New SqlCommand(qry, myconn)
mycmd.ExecuteNonQuery()
myconn.Close()
End Sub

Related

Cannot Add new row to database with DataAdapter.insertCommand vb.net

I try to add new record to the database with command DataAdapter.InsertCommand. But I don't know why It doesn't insert new record to database
Here is my code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO StudentData(StudentID) VALUES (#studentid)"
cmd.Parameters.AddWithValue("#studentid", "123")
Try
cnn.Open()
da.InsertCommand = cmd
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
cnn.Close()
End Try
End Sub
Please help me find out what's wrong with it?
I'm all in favor of using what works and I see the solution above works. The advantage of using a dataadapter however, is that it wraps all the sql commands needed for the CRUD operations of the datatable. You can configure your own commands or let visual studio configure them automatically by using a sqlcommandbuilder. Then once you have the adapter configured all you need to do is something like this
Dim myds As New DataSet()
Dim mytable as New datatable()
myds.Tables.Add(mytable)
Dim myconstr As String = "ConnectionStringtoDataBase"
Dim myconn As New SqlConnection(myconstr)
Dim da as new SqlDataAdapter( “SELECT * FROM StudentTable”,cnn)
Dim mycb As New SqlCommandBuilder(da)
da.Fill(mytable)
Dim myrow As DataRow = mytable.NewRow()
myrow("ID") = "thestudentid"
myrow("StudentName") = "John doe"
myrow("StudentID") = 12345
myrow("StudentClass") = "VB 101"
mytable.Rows.Add(myrow)
da.Update(mytable)
The CommandBuilder will automatically add insert, update and delete commands to the dataadapter (if your select command is one table only, otherwise you'll have to configure it manually).

create table in access database using Adox in vb

I'm using a Windows form application in Visual Basic 2012 to create a new Microsoft Access database using .ADOX. I can create the database but can't create a table in the database.
My code is :
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
Dim tablename As String = "Users"
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [ " & tablename & "] ([Username] varchar(50)), ([Password] varchar(50)), ([E-mail] varchar(75))"
mycommand = New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
MsgBox("Database created")
End Sub
End Class
The error is get is:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in CREATE TABLE statement.
Any help is appreciated.
EDITED:
The following code gets past the first error but i now get a field definition error, i know the code should work as it works with adding a number field, possible because the field type in access is short text and long text but anything i've tried doesn't seem to work.
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [Users] (Username Varchar(50), Password Varchar(50), E-mail Varchar(50))"
mycommand = New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
MsgBox("Database created")
End Sub
End Class
Looks like you have too many parenthesizes, but I think the actual error is coming from the leading space you have in your query:
V
str = "CREATE TABLE [ " & tablename & "]
Try changing it to:
str = "CREATE TABLE [" & tablename & "] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(75))"
Make sure you dispose of your objects, preferably in a using block:
Example:
Using cn As New OleDb.OleDbConnection(mdb)
cn.Open()
Using cmd As New OleDb.OleDbCommand(str, cn)
cmd.ExecuteNonQuery()
End Using
End Using
At the end the code looks like this:
Imports ADOX
Imports System.Data.OleDb
Public Class Form1
Dim mycommand As OleDbCommand
Dim myconnection As OleDbConnection
Dim myReader As OleDbDataReader
Dim str As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim cat As New Catalog()
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb;Jet OLEDB:Engine Type=5")
cat = Nothing
Using myconnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Test\DDL.mdb ")
myconnection.Open()
str = "CREATE TABLE [Users] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(50))"
Using mycommand As New OleDb.OleDbCommand(str, myconnection)
mycommand.ExecuteNonQuery()
End Using
End Using
MsgBox("Database created")
End Sub
End Class

check values of column in sql

I am trying to collect values from a database, and if they are X value sett he background colour to green.
Basically, I have a Rota system, and if the user is working, then change the background colour. The select * will only bring back 1 row ever.
Imports System.Data.SqlClient
Imports System.Data.OleDb
Public Class Form4
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form4_Load(sender As Object, e As EventArgs)
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
Dim strSQL As String = "SELECT * from Users"
Dim da As New SqlDataAdapter(strSQL, Con)
Dim ds As New DataSet
da.Fill(ds, "Users")
With cboname
.DataSource = ds.Tables("Users")
.DisplayMember = "Name"
.ValueMember = "Id"
.SelectedIndex = 0
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Con As SqlConnection
Dim cmd As New OleDbCommand
Dim sqlstring As String
Dim connstring As String
Dim ds As DataSet
Dim da As SqlDataAdapter
connstring = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Assignment.mdf;Integrated Security=True;Connect Timeout=30"
Con = New SqlConnection(connstring)
Con.Open()
sqlstring = ("SELECT * FROM Rota WHERE UserId ='" & cboname.SelectedIndex & "' and ID ='" & dtp1.Value & "'")
da = New SqlDataAdapter(sqlstring, Con)
ds = New DataSet
da.Fill(ds, "Rota")
End Sub
End Class
After this, I understand I need to get a few IF statements, but I am unsure on how to construct them.
To check a value in a DataSet use first get a DataTable inside of it, then a DataRow, then check one of the field values:
ds.Tables(0).Rows(0)("{field name}");
So to change the color based on some value:
If ds.Tables(0).Rows(0)("{field name}") = "Red" Then
textbox1.BackColor = Color.Red
End If
Some other comments:
A DataSet may be a bit heavy for getting one value (unless you're binding to a control). You can just use ADO.NET objects and use ExecuteScalar)
It's safer to use parameters instead of concatenating SQL statements (prevents SQL Injection and errors from special characters)
You can refactor your code to put the connection string in a single location rather than duplicating it across methods.

“The ConnectionString property has not been initialized” error in VB.NET

Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
How can i avoid this error and make it work?
Here are my codes:
Imports System.Data.OleDb
Public Class frmLoginPage
Dim con As New OleDbConnection
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("Select*from tblPassword", con)
da.Fill(dt)
Dim newRow As DataRow = dt.NewRow
With newRow
If .Item("Username") = txtUsername.Text And .Item("Password") = txtPassword.Text Then frmMainMenu.ShowDialog() Else MsgBox("The username or password you entered was incorrect, please try again!", MsgBoxStyle.Critical, "Information")
End With
End Sub
You have instantiated an OleDbConnection object, but you haven't set the connectionstring property so it doesn't know where it should connect to. You also haven't opened it. Your code should look something like:
Dim myConnection As OleDbConnection = New OleDbConnection()
myConnection.ConnectionString = myConnectionString
myConnection.Open()
' execute queries, etc
myConnection.Close()
This Problem Occurs when you donot consider making a new connection
The solution is very simple, all you have to do is to make
Dim conString as string = "Your connection string here"
Dim con As new OleDbConnection
con.connectionSting= ConSting
con.open()
'now simply write the query you want to be executed
'At the end write
con.close()
this will solve your problem.
if it doesn't solve your problem post reply I will try to solve it.
You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)

adding a column to a SQL table in VB using ADO.NET commands

I am interested in a minimal set of instructions that allow me to add a column into an existing table in visual basic using ado.net components. My database is made in sql server. I would greatly appreciate a practical commentary to the code as that works best for me
edit 1
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connString As String = "Data Source=THE_SHOGUNATE\SQLEXPRESS;Initial Catalog=le_database;Integrated Security=True"
Dim conn As New SqlConnection(connString)
conn.Open()
Dim comm As New SqlCommand("SELECT denumire FROM Reparatii", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
Dim dt As New DataTable
dt.Load(reader)
ListBox1.DataSource = dt
ListBox1.DisplayMember = "denumire"
conn.Close()
conn.Open()
Dim comm As New SqlCommand("ALTER TABLE reparatii ADD durata_executie INT", conn)
conn.Close()
End Sub
End Class
Here's a set of instructions meant for testing purposes and some wishful coding
conn.Open()
Dim comm As New SqlCommand("ALTER TABLE reparatii ADD durata_executie INT", conn)
comm.ExecuteNonQuery()
I would also suggest using a using statement to automatically dispose of objects.