Using Object to execute SQL statements in Visual Studio - database

I apologize if my question is simple, but I have done a lot of looking on the Internet and I am having trouble finding a solution.
I have a database connected to Visual Studio where I used the "Connect to Database..." wizard to establish the connection. In the Server Explorer in Visual Studio, I see I have a Data Connection called "newreptDBtest.accdb", and a Server named Mandrew.
Basically I would like to execute SQL statements on this database when clicking a button. So I have a button on a form, and it has the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sqlconn As New SqlConnection
sqlconn.ConnectionString = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Try
sqlconn.Open()
Catch ex As Exception
MessageBox.Show("Error on connection")
End Try
If sqlconn.State = 1 Then
MessageBox.Show("Success!")
End If
End Sub
In General Declarations, I have:
Imports System.Data.SqlClient
Perhaps because it's not a SQL database? I'm not sure. Either way, I have not been able to achieve the "Success!" from the MessageBox. Once I've gotten that, I'm sure I can figure out how to create SQL statements to return certain rows or single pieces of information.
In the newreptDBtest, the table I'd like to be executing queries on is called newrept, and the connection string to the database is:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Andrew\Documents\newreptDBtest.accdb"
tl;dr:
How do I use an object (such as a button) to execute SQL queries on a table inside a database already connected to my project?
Thanks in advance

The classes that you need to use for accessing an MS Access database file are in the System.Data.OleDb namespace. Try this:
Dim ConnString As String = "server=Mandrew;Initial Catalog=newreptDBtest.accdb"
Dim SqlString As String = "put your query here, e.g. Select * From Contacts"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
'access the data using the reader, e.g. reader("ColumnName")
End While
End Using
End Using
End Using
Taken from here
Obviously, you will need to modify it to fit your query but this hightlights the fact that you need to use OleDbConnection to connect to an MS Access file.

Related

SQL Server database population pre-existing Data Table and fields (FORM). NO database file

Here is my general understanding of database from what I read so far: Save / Update / Delete to pre-existing file made that binds to form thru SQL.
Here is what I am trying to do - I have a pre-made Data Table in Form with all columns defined. Once app is closed or certain functions ran, I need that data to be saved / updated in SQL (on local). Once app is open I need all that data to be preserved.
So far I have NOT found a single solution to it anywhere most refer to binding to an existing file. When I worked with Excel data transfer cells had to be defined and referenced in form for population.
My assumption is when a database from VB.NET is used, table with values can be created automatically saved/loaded/updated. However this is only my assumption since I never worked with SQL before. I am not sure if I need to manage an actual database file I created with all the values and then bind them to data table. For example DataTable cell XX to database column XX.
Here is what I done so far I have created database and added to my project. I tried few codes and I keep getting Dataset Empty even though there is Data in Table I tried to use DataTable as well but so far nothing has worked.
Please suggest on what I am doing wrong also additional information regards to databases will be great. As per previous I do know how binding works when actual file exist. But creating and managing is confusing to me since I keep thinking there should be a binding file.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "SELECT BN FROM DataTable" ' BN is my column name and DataTable is the name of my Table where data gets populated. This is also confusing to me How does it know which value is what? Is there are space/word/characters requirements?
' adapter.TableMappings.Add("DataTable", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds)
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
Code I use to Create /Save Database. As per previous all columns/formats are pre-made, loaded.
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
sql = "Select BN FROM DataTable"
adapter.TableMappings.Add("BN", sql)
If DataTable.RowCount > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf DataTable.RowCount = 0 Then
MsgBox("Empty data")
End If
End Sub
Please see more info below:
Data Table columns/format are structured for visual representation.
When User start the App Database can be empty/Can contain Values.
When users Runs certain function Closes App values are save and only values.
If I would you an MS Access I would structure same table/values and cross reference it with form values. Form Values come from outside source and Format/Qty is always known.
Hope this helps to have a cleaner look at my issue. Perhaps SQL is not a right choice for me? Does SQL needs to be build before value manipulation.
UPDATE: I Got rid of the Invalid Object error. Table had to be created 1st as I originally thought. However, My DataSet always comes up as EMPTY when I try to save... Cells do contain BN data as" 1,2, ....) Even if I to remove "If" logic Save and Load table comes out as empty. Something does load because when I try to ADD BN it tells me binding bla bla bla(different issue)
CODE:
Private Sub SaveData()
Dim connetionString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Dim sql As String = "SELECT BN FROM DataTable_d"
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet()
adapter.TableMappings.Add("BN", sql)
If ds.Tables.Count > 0 Then
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Update(ds, "BN")
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection !" & vbCrLf & Err.Description)
End Try
ElseIf ds.Tables.Count = 0 Then
MsgBox("Empty data")
End If
End Sub
UPDATE: I got all the things working but I can't save multiple rows..... Could really use some help
In your SQL query remove WHERE DataTable ='. This statement is looking for a column name DataTable which I assume does not exist. The WHERE clause is used to help filter your query. You only use WHERE on column names in your table.
For instance:
SELECT BN FROM DataTable
will return all values from the BN column from DataTable.
Note that if you have multiple columns, the above query will still only return values from BN.
SELECT * FROM DataTable
will return every value in DataTable.
A helpful site to look at documentation for SQL is w3schools.
Let's start with just displaying some data. Add a DataGridView to a Form. You can call LoadData() from a button. I am not very sure of you connection string but give it a try.
Private dt As DataTable
Private sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Private Sub LoadData()
'***EDIT*** Add instantiation line
dt = New DataTable()
'The Using...End Using blocks will close and dispose your database objects
'even if there is an error
Using cn As New SqlConnection(sql)
'You can pass the command text and the connection directly to the constructor
'In the select statement use the actual names of the field and table as they appear in the database.
Using cmd As New SqlCommand("Select BN From [Insert the name of the table in the database]", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
This is the simplest way I can think of to display data. We will proceed with changing the data once this works. If you get an error on cn.Open() We will have to work on the connection string.
****EDIT****
Private Sub TestConnection()
Dim sql As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data_Ant.mdf;Integrated Security=True;Connect Timeout=30"
Using cn As New SqlConnection(sql)
cn.Open()
End Using
End Sub

Error connecting to SQL Server 2012 with VB.NET 2010

I have been trying to fix a project which already use a 100% connections to Oracle. They are trying to upgrade the project to start using SQL Server 2012 Management Studio. But I'm having issues connecting to the database. We use Windows authentication.
I can login fine directly to SQL Server 2012 using Management Studio and Windows authentication. If I create a fresh new WindowsApplication1 project to test the connection code it works fine, I'm using this code (and get an error is at conn.Open()):
Imports System.Data.SqlClient
Public Class Open_Filing_Image
'Create ADO.NET objects.
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private results As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Create a Connection object.
Dim connStr As [String] = "Server=servername; Database=dbname; Integrated Security=True"
myConn = New SqlConnection(connStr)
'Create a Command object.
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT DdocName FROM dbo.Document WHERE XAlaskaID = '72010' and DdocType = 'Filings'"
'Open the connection.
Try
myConn.Open()
MsgBox("Connection Open ! ")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
myReader = myCmd.ExecuteReader()
'Concatenate the query result into a string.
Do While myReader.Read()
results = myReader.GetValue(0)
Loop
'Display results.
Dim documentID As String = results
Dim outPath As String = "http://address.internet`enter code here`/" + documentID + (".pdf")
System.Diagnostics.Process.Start(outPath)
'Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
End Class
Error message:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The specified data could not be decrypted.
Thank you.
Fix it doing some research and some assistance by another programmer:
The project had a Bcrypt reference that block the connections to SQL. I delete all Bcrypt and add transport credentials to Windows in the app.config. any way thanks guys.

Visual Studio 2010 - cannot reconnect to SQL Server instance after project is saved

Using Visual Studio 2010 I am able to start a new project using ADODB (Microsoft ActiveX Data Objects 6.1 Library COM 6.1.0.0) to connect to MS Access and SQL Server, save the project, re-open the project and it all works as expected. BUT when I do this trying to connect to a SQL Server Instance it will work until I save the project after which I always get the error: "SQL Server does not exist or access denied".
Here is the code for my test console application;
Module Module1
Sub Main()
Dim cn As New ADODB.Connection()
Dim rs As New ADODB.Recordset()
Dim cnStr As String
' Modify this connection string to reflect your server and logon information.
' Store the connection to a variable to be used throughout this example.
cnStr = "Provider=SQLOLEDB;Initial Catalog=Firehouse;Data Source=devclstr\devclstr;" & _
"User ID=xxx;Password=xxx;"
' 1. Connect through the Connectionstring property.
cn.ConnectionString = cnStr
cn.Open()
rs.Open("select * from usr_sec", cn)
Dim da As New System.Data.OleDb.OleDbDataAdapter()
Dim ds As New DataSet()
da.Fill(ds, rs, "products")
Console.Write("There are " & ds.Tables(0).Rows.Count.ToString & " total users.")
Console.ReadLine()
rs = Nothing
cn.Close()
cn = Nothing
End Sub
End Module
This will work only in the following scenario: start new console project, enter the code, add the "ActiveX Data Objects 6.1 Library" reference, and it runs as expected. As soon as I save it each subsequent execution gives me the following error:
System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2147467259
HResult=-2147467259
Message=[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
Source=Microsoft OLE DB Provider for SQL Server
StackTrace: at ADODB._Connection.Open(String ConnectionString, String UserID, String Password, Int32 Options)
Please share any insight in how to resolve this problem
Normally, I'd advise against using the COM approach, when there are built in connectors, so instead, something like:
Imports System.Data.SqlClient;
Module Module1
Sub Main()
' Modify this connection string to reflect your server and logon information.
Dim cnStr As String = "Initial Catalog=Firehouse;Data Source=devclstr\devclstr;User ID=xxx;Password=xxx;"
Using con as New SqlConnection(cnStr)
con.Open()
Using cmd as New SqlCommand("select * from usr_sec", con)
Using da As New SqlDbDataAdapter()
Dim ds As New DataSet()
da.Fill(ds, rs, "products")
Console.Write(String.Format("There are {0} total users.", ds.Tables(0).Rows.Count))
Console.ReadLine()
End Using
End Using
End Using
End Sub
End Module

Creating a SQL Server database for the first time at run time

I want to create a SQL Server database at runtime in my vb.net project. I know how to actually code the database but I am wondering where should I actually put the code? Should I be putting the code in the start up form or should it go into a class on it's own? Also, this project will be going on more than one pc at a particular site, so I only want the database to be created the first time the project is activated and then just be able query the database on different pcs after that. How do I do this? All help on this matter would be greatly appreciated.
EDIT:
Ok, so I should have been clearer on this. The project is going to be on 2 different pcs, it is for visitors entering a business. The pcs will be in reception and security. I need both pcs to access the same database with the same details in it. I don't want to have two different databases where details have to be put in twice. For example, if I enter at reception today and then go through security tomorrow, then all I should have to enter in security is why I'm entering the business again, I shouldn't have to put my details in a second time. How do I go about this? As I already said, I know how to code the database, but I want to know how to do what I stated in my question.
Thanks in advance for all help given.
If you add the code in module or in form load then it will execute all the time when the form loads. it is wasting of time to check whether the database exist or not in each run. So it is better to place a button with text "Create database" for this purpose(or menu item). it's click event will load the database. the following code can be used to create the database dynamically on button click
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'creating and initializing the connection string
Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;Pooling=False")
'since we need to create a new database set the Initial Catalog as Master
'Which means we are creating database under master DB
Dim myCommand As String //to store the sql command to be executed
myCommand = "CREATE database my_db" //the command that creates new database
Dim cmd As SqlCommand = New SqlCommand(myCommand, myConnectionString) // creating command for execution
Try
cmd.Connection.Open() //open a connection with cmd
cmd.ExecuteNonQuery() //Execute the query
cmd.Connection.Close() //Close the connection
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
'Creating table to the dynamicaly created database
Try
Dim cn As SqlConnection = New SqlConnection("Data Source=(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;Pooling=False")
'here the connection string is initialized with Initial Catalog as my_db
Dim sql As String //sql query string
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg varchar(50) NULL)"
cmd = New SqlCommand(sql, cn) // create command with connection and query string
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Catch
MsgBox(" Already existing table", MsgBoxStyle.Critical, " MaS InfoTech- Warning")
End Try
End Sub

How do I connect to SQL Server with VB?

I'm trying to connect to a SQL server from VB. The SQL server is across the network uses my windows login for authentication.
I can access the server using the following python code:
import odbc
conn = odbc.odbc('SignInspection')
c = conn.cursor()
c.execute("SELECT * FROM list_domain")
c.fetchone()
This code works fine, returning the first result of the SELECT. However, I've been trying to use the SqlClient.SqlConnection in VB, and it fails to connect. I've tried several different connection strings but this is the current code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = "data source=signinspection;initial catalog=signinspection;integrated security=SSPI"
Try
conn.Open()
MessageBox.Show("Sweet Success")
''#Insert some code here, woo
Catch ex As Exception
MessageBox.Show("Failed to connect to data source.")
MessageBox.Show(ex.ToString())
Finally
conn.Close()
End Try
End Sub
It fails miserably, and it gives me an error that says "A network-related or instance-specific error occurred... (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I'm fairly certain it's my connection string, but nothing I've found has given me any solid examples (server=mySQLServer is not a solid example) of what I need to use.
Thanks!
-Wayne
You are using an ODBC DSN as a SqlClient server name. This is not going to work. You have to use a SqlClient connection string, and for SqlClient the DataSource property is the server name or a SQL Native Client server alias (which is not the same as an ODBC DSN).
Replace signinspection with the actual name of your SQL Server host. If is a named instance or listening on a non default port, you have to specify that too, eg: hostname\instancename
Check out connectionstrings.com for samples. It looks like in your python example, you are accessing the DB via ODBC.
The string you are using is connecting with the built in .NET SQL Server DB provider, so you need to use an ODBC connection string OR change your data source to the actual server name (if no other instances) or servername/instance name.
Sure your Server and Database have the same name?
Here you have a link that would allow you to generate a connection string and test it
http://blogs.msdn.com/dhejo_vanissery/archive/2007/09/07/One-minute-Connection-string.aspx.
Well, I went ahead and used an ODBC Connection. It appears that that is what I was wanting in the first place.
In order to do use the ODBC I had to go to http://support.microsoft.com/kb/310985 and install a few files. Following the directions I came up with the following code that seems to work just fine:
Dim conn As OdbcConnection
conn = New OdbcConnection("DSN=SignInspection")
Dim mystring as String = "SELECT * FROM list_domain"
Dim cmd As OdbcCommand = New OdbcCommand(mystring, conn)
Dim reader As OdbcDataReader
Dim columnCount As Integer
Dim output As String
Dim data as Object() = New Object(10) {}
conn.Open()
MsgBox("Connected!")
reader = cmd.ExecuteReader()
While reader.Read()
columnCount = reader.GetValues(data)
output = ""
For i As Integer = 0 To columnCount - 1
output = output & " " & data(i).ToString()
Next
Debug.WriteLine(output)
End While
conn.Close()
Of course I'll have it cleaned up a lot, but I figure maybe someone will end up looking for the same solution, and maybe they'll see my code before they spend too much time.
ed. columsCount -> columCount
You might want to take a look on Microsoft Enterprise Library Data Access Application Block in order to make it easier to connect and to support multiple underlying datastores.
Good success! =)

Resources