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
Related
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
I'm struggling to grasp VB as I'm new to programming. I am creating a program which displays a result (namely a link to a website) based on a users' filters. I've done this so far, which just selects the size filter. However, I don't know how to write the code that will check the database for the users' preference and output an appropriate link in the form of a label. Is it as simple as just printing DataTable or am I totally wrong? Any help would be greatly appreciated.
Here is my code so far:
Imports System.Data.OleDb
Public Class frmFilters
Dim provider As String
Dim dataFile As String
Dim ConnString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private ConStr As String = "My Connection String"
Private Sub buttonSearch_Click(sender As Object, e As EventArgs) Handles buttonSearch.Click
provider = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "H:\Visual studio files\Project\CMPC\partLists.accdb"
End Sub
Private Function GetPartData(filterMicroATX As Integer, filterATX As Integer) As DataTable
Dim dt As New DataTable
Dim sql = "SELECT * FROM partList WHERE
[size] > #MicroATX
And [size] < #ATX;"
Using con As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sql, con)
With cmd.Parameters
.Add("#MicroATX", OleDbType.Integer).Value = filterMicroATX
.Add("#ATX", OleDbType.Integer).Value = filterATX
End With
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
Me.Close()
End Sub
End Class
I made a table in SQLServer and the idea of code is to fill the blank and click Insert and a new user will be added to database and the DataGridView, but I got this error:
Invalid object name 'Users'.
This error appear after I click the Insert button:
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim connection As New SqlConnection("Data Source=LAPTOP-DLGJAU3D;Initial Catalog=master;Integrated Security=True")
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
EmployeeListDataGridView.DataSource = GetEmployeeList()
End Sub
Private Function GetEmployeeList() As DataTable
Dim dtEmployees As New DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmd As New SqlCommand("SELECT * FROM dbo.EMPLOYEES", conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
dtEmployees.Load(reader)
End Using
End Using
Return dtEmployees
End Function
Private Sub BTN_INSERT_Click(sender As Object, e As EventArgs) Handles BTN_INSERT.Click
Dim command As New SqlCommand("insert into Users(Fname, Lname, age) values('" & TextBoxFN.Text & "','" & TextBoxLN.Text & "'," & TextBoxAGE.Text & ")", connection)
connection.open()
If command.ExecuteNonQuery() = 1 Then
MessageBox.Show("New User Added")
Else
MessageBox.Show("User Not Added")
End If
connection.close()
End Sub
End Class
So I have created a database and want to insert information from my form in VB to the database. I have linked and coded it however, I keep getting this error message: Syntax error in INSERT INTO Statement . I have looked at many other similar questions however none of the solutions work. Here is my code:
Imports System.Data.OleDb
Class Form1
Dim Provider As String
Dim DataFile As String
Dim ConnString As String
Dim MyConnection As OleDbConnection = New OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
DataFile = "C:\Users\Documents\Visual Studio 2012\Projects\DatabaseTest\DatabaseTest\Database.accdb"
ConnString = Provider & DataFile
MyConnection.ConnectionString = ConnString
MyConnection.Open()
Dim Strng As String
Strng = "INSERT INTO [Table1]([StudentName], [StudentScore] Values (?,?))"
Dim Cmmnd As OleDbCommand = New OleDbCommand(Strng, MyConnection)
Cmmnd.Parameters.Add(New OleDbParameter("StudentName", CType(txtName.Text, String)))
Cmmnd.Parameters.Add(New OleDbParameter("StudentScore", CType(txtScore.Text, String)))
Try
Cmmnd.ExecuteNonQuery()
Cmmnd.Dispose()
MyConnection.Close()
txtName.Clear()
txtScore.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Any help would be much appreciated!!
End brace in the wrong place. You also do not need to convert the Text property to a string in the parameters.
Imports System.Data.OleDb
Class Form1
Dim Provider As String
Dim DataFile As String
Dim ConnString As String
Dim MyConnection As OleDbConnection = New OleDbConnection
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= "
DataFile = "C:\Users\Documents\Visual Studio 2012\Projects\DatabaseTest\DatabaseTest\Database.accdb"
ConnString = Provider & DataFile
MyConnection.ConnectionString = ConnString
MyConnection.Open()
Dim Strng As String
Strng = "INSERT INTO [Table1]([StudentName], [StudentScore]) Values (?,?)"
Dim Cmmnd As OleDbCommand = New OleDbCommand(Strng, MyConnection)
Cmmnd.Parameters.Add(New OleDbParameter("StudentName", txtName.Text))
Cmmnd.Parameters.Add(New OleDbParameter("StudentScore", txtScore.Text))
Try
Cmmnd.ExecuteNonQuery()
Cmmnd.Dispose()
MyConnection.Close()
txtName.Clear()
txtScore.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I am having a problem trying to get the contents of a list box into and SQL string via a variable(moon)
Here are 3 SELECT strings from the main body of code below.The last two strings work fine
but the first one doesn't.That's the one where I try and place the variable into the code
I have tried a few variations on the code but nothing seems to work.Does anybody have any suggestions.
THE SQL STRINGS:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon "' ", myConnection) 'fails
da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works{
MAIN CODE BODY
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.Odbc
Imports System.Data.DataTable
Public Class Form1
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As DataSet = New DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim moon As String
moon = ListBox1.Text
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
connString = provider & dataFile
myConnection.ConnectionString = connString
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection) 'fails
'da = New OleDbDataAdapter("SELECT * FROM books", myConnection) 'works
'da = New OleDbDataAdapter("SELECT * FROM books WHERE author = 'molly brown' ", myConnection) 'works
da.Fill(ds, "books")
' replace "items" with the name of the table
' replace [Item Code], [Description], [Price] with the columns headers
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
End Sub
End Class
Best practice is to use a new connection object for each call to the database, define objects with the smallest scope possible, and to use parameterized queries instead of substituting the value into your sql string.
Under no circumstances should you ever use string manipulation to put a user-selected value into your sql statement! Code like this is very bad:
da = New OleDbDataAdapter("SELECT * FROM books WHERE [author] = '" & moon & "' ", myConnection)
Imagine what would happen in this example if you have an author like "Patrick O'Neil". There are many ways this problem can be further abused to cause real damage to your database, application, and users. Just don't use string concatenation for this.
Do it like this instead:
Public Class Form1
Private Const provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Private Const dataFile As String = "C:\Documents and Settings\james\Desktop\Authors.accdb" ' change to access database location on your computer
Private connString As String = provider & dataFile
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ds As New DataSet()
'Set a special placeholder for your value as part of a *constant* sql statement
Dim sql As String = "SELECT * FROM books WHERE [author] = ? "
Using cn As New OleDbConnection(connString), _
cmd As New OleDbCommand(sql, cn), _
da As New OleDbDataAdapter(cmd)
'Set the value for that placeholder via a query parameter
'Parameters work best when you set the actual type and length
' to match your database. I had to guess at the length here.
cmd.Parameters.Add("?", OleDbType.NVarChar, 50).Value = Listbox1.Text
da.Fill(ds, "books")
End Using
DataGridView1.DataSource = ds.Tables("books")
DataGridView1.Refresh()
End Sub
End Class