Getting the connection string from an imported source - sql-server

I have added a new datasource from a SQL-server into my project and want to create a SQLConnection (using System.Data.SqlClient).
During the datasource creation I saved the Connectionstring as Dev_DBConnectionString and want to use this now but I have no clue how. I tried
ConsoleApplication1.Properties.Settings.Default.masterConnectionString
(this is how some c# tutorials doing it) but get the error: Properties is not a Member of ConsoleApplication1. I have checked some vb.net tutorials (e.g.) but they are using the descriptive way like
Data Source=MSSQL1;Database=AdventureWorks;" & "Integrated Security=true;
But I guess that the string is already somewhere in my system. Anyone who can help me out here?

FIRST
You have to setup your connection!
Imports System.Data.SqlClient
Imports System.Data
Public Class SQLTools
Inherits System.Windows.Forms.Form
Private Const SqlString As String = Dev_DBConnectionString
Private myConn As SqlConnection
Private myCmd As SqlCommand
Private myReader As SqlDataReader
Private Sub Conn()
myConn = New SqlConnection(SqlString)
End Sub
Now you can enjoy your DB connection
It's time to do what you want! you just need to call Conn() to setup everything and than you have to open the connection using MyConn.Open()
Dev_DBConnectionString problems
You can always write it again.
e.g.
Private Const SqlString As String = "Server=****;Database=****;User ID=****;Password=****;Integrated Security=SSPI;"

Related

Change connection EF at runtime in WPF app

I have a WPF app that I'd like to change the connection string programmatically when the app loads. I use the Database-First approach for EF.
I spent a lot of time implementing various solutions found online including stack overflow and can't seem to get it to work.
The most common way seems to be to modify the Entity partial class. When I do this I get the following error at runtime:
Additional information: The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
I got the same error implementing various other ways as well. If someone could please help me implement a way to change the connection string at runtime I'd greatly appreciate it.
My current implementation is taken from this example solution:
Changing Databases at Run-time using Entity Framework
Implementation:
App.config containts the connection string and name
Partial class added with same name as Entity class:
Imports System.Data.Entity
Imports System.Data.EntityClient
Imports System.Data.SqlClient
Partial Public Class MyEntityName
Inherits DbContext
Public Sub New(ByVal connString As String)
MyBase.New(connString)
End Sub
End Class
In my Application.xaml code file I set a global string variable by calling a method that builds the EntityConnectionStringBuilder. This global string variable is then passed into an entity constructor.
Imports System.Reflection
Imports DevExpress.Xpf.Core
Imports System.Data.EntityClient
Class Application
Public Sub New()
entityConnStr = BuildConnectionString("[MyDataSource]", "[MyDatabase]")
End Sub
Private Function BuildConnectionString(ByVal DataSource As String, ByVal Database As String) As String
' Build the connection string from the provided datasource and database
Dim connString As String = "data source=" & DataSource & ";initial catalog=" & Database & ";persist security info=True;user id=[user];password=[password];trustservercertificate=True;MultipleActiveResultSets=True;App=EntityFramework""
' Build the MetaData... feel free to copy/paste it from the connection string in the config file.
Dim esb As New EntityConnectionStringBuilder()
esb.Metadata = "res://*/DB.[MyEntityName].csdl|res://*/DB.[MyEntityName].ssdl|res://*/DB.[MyEntityName].msl"
esb.Provider = "System.Data.SqlClient"
esb.ProviderConnectionString = connString
' Generate the full string and return it
Return esb.ToString()
End Function
Usage:
Using context = New MyEntity("entityConnStr")
Public connection variable string:
Public entityConnStr As String
I think you should remove the quotes when you pass the connection string to the constructor. You want to use the variable contents, not the variable name.
Use this:
Using context = New MyEntity(entityConnStr)
Instead of this:
Using context = New MyEntity("entityConnStr")

VB.Net connection

I'm slowly transitioning to VB.Net and it seems like the simplest of things are completely different. I'm trying to do a connection to SQL Server and just grab some data. I've tested the connection and it's fine. Now I'm trying to simply select some data from the server and display the first name in the Msgbox (or anything for that matter). Here is the code I've gotten so far....
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Public conn As New SqlConnection("data source=Tuys1;initial catalog=DDDBuyer; user ID=userID; password=password")
Private dA As New SqlDataAdapter("Select FirstName, LastName from tblBuyers where Buyerid=1473", conn)
Private dS As New DataSet
End Class
I'm not really sure how to go from here... I understand there is something like
.hasRows
if ds.hasrows then
msgbox = "HELLO"
End if
or something like displaying the FirstName in txtFirstName
I am trying to get an idea of how ths works and after some research it's hard to find a specific example that would help me do what I'm trying to accomplish.
Dim custAdapter As SqlDataAdapter = New SqlDataAdapter( _
"SELECT * FROM dbo.Customers", customerConnection)
Dim ordAdapter As OleDbDataAdapter = New OleDbDataAdapter( _
"SELECT * FROM Orders", orderConnection)
Dim customerOrders As DataSet = New DataSet()
custAdapter.Fill(customerOrders, "Customers")
ordAdapter.Fill(customerOrders, "Orders")
Dim relation As DataRelation = _
customerOrders.Relations.Add("CustOrders", _
customerOrders.Tables("Customers").Columns("CustomerID"), _
customerOrders.Tables("Orders").Columns("CustomerID"))
Dim pRow, cRow As DataRow
For Each pRow In customerOrders.Tables("Customers").Rows
Console.WriteLine(pRow("CustomerID").ToString())
For Each cRow In pRow.GetChildRows(relation)
Console.WriteLine(vbTab & cRow("OrderID").ToString())
Next
Next
As explained here

Why is my db not connecting?

I am newbie to vb.net and i am trying to connect with a sql server.
my connection string here is:
<add name="ConString" connectionString="Data Source=LV-SC294\SQLEXPRESS;Initial Catalog=master;Persist Security Info=True;User ID=1111;Password=111111" providerName="System.Data.SqlClient"/>
Here is my DBConnection file where i connect to the server,
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.Provider
Imports System.Configuration
Imports System.Web.Services
Imports System.Data.Odbc
Namespace CATTool
Public Class DBConnection
Protected con As OdbcConnection
Dim b As Boolean
Protected rs As Object
Public Function Open(Optional ByVal connection As String = "ConString") As Boolean
con = New OdbcConnection(ConfigurationManager.ConnectionStrings("ConString").ConnectionString)
Try
b = True
If (con.State.ToString <> "open") Then
con.Open()
End If
Return b
Catch ex As Exception
Return False
End Try
End Function
and finally here is where i call my DbConnection.. Here i am trying to set up the connection with the server and also execute the query to fetch rows. How ever the connection is not established.It keeps throwing the message "Connection didn't establish"
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Imports CAT_Tool.CATTool
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
Namespace CAT_Tool
Public Class SummaryController
Inherits System.Web.Mvc.Controller
'
' GET: /Summary
Protected DB As DBConnection = New DBConnection()
Private Property Val As Object
Function Index() As ActionResult
Return View()
End Function
Function Summary() As ActionResult
Return View()
End Function
<WebMethod()> _
Public Function Get_Territory()
MsgBox("Filling Territory")
Dim Query As String = "select distinct Territory from dbo.CWS_WEBTOOL_USG"
Dim dbcon As Boolean = DB.Open()
If (dbcon = True) Then
MsgBox("Connection Established")
Val = DB.selectdata(Query)
DB.Close()
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In Val.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In Val.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
MsgBox("Returning values")
MsgBox(rows)
Return serializer.Serialize(rows)
Else
MsgBox("Connection Did'nt Establish")
Return Content(dbcon.ToString)
End If
Return View()
End Function
My sql server details are as follows:
ServerName = LV-SC294\SQLEXPRESS
Authentication : SQLServer Authentication
I agree with #AllanS.Hansen that it is best to use System.Data.SqlClient to access SQL Server from managed code. Your connection string is a proper SqlClient connection string, although one usually specifies an application database rather than the master system database.
If you want to use ODBC (e.g. same code supporting different DBMS systems), you'll need to change the connection string and provider in the config file. For example, using the latest SQL Server ODBC Driver:
<add name="ConString" connectionString="Driver={ODBC Driver 11 for SQL Server},Server=LV-SC294\SQLEXPRESS;Database=YourDatabase;UID=1111;PWD=111111" providerName="System.Data.Odbc"/>

database connection with a chart

I have been trying to figure this out for a few days but every time I try and fix it I encounter the same error. I am trying to implement the data from my database into a candlestick style chart.Every time I run it i'm faced with this same error:
"An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: IErrorInfo.GetDescription failed with E_FAIL(0x80004005)."
I have used a combination of the limited resources given to me and code that I found here on a previously answered question to create the following code.
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim myConnection As OleDbConnection = New OleDbConnection
Dim provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile As String = "C:\Users\Ian\Documents\A2 Woking\Computing\Database1\Database_data_source .accdb"
Dim DatabasePass As String = "DatabasePW"
Dim connString As String = provider & dataFile
Dim execute As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
myConnection.ConnectionString = connString
Dim objDataAdapter As OleDbCommand = New OleDbCommand("Select Time, Open, High, Low, Last FROM EUR_USD_TB", myConnection)
myConnection.Open()
execute = objDataAdapter.ExecuteReader
While execute.Read
chartTemplate.Series("dataSeries").Points.AddXY(execute("Time"), execute("Low"), execute("High"), execute("Open"), execute("Last"))
End While
' Close the reader and the connection
execute.Close()
myConnection.Close()
End Sub
End Class
Any help would be appreciated i'm sure its something annoyingly simple I don't get.
The path is correct---
The database is not protected by a password, that variable is for later---
The query works in access---
This same code works perfectly for accessing a separate table in my login

VB.NET/SQL System.Argument Exception

I am brand new to programming, and I have been encountering several errors as I work to build an application. The additional information section of the Visual Studio error box delivers the following message:
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Format of the initialization string does not conform to specification starting at index 0.
This occurs as the application attempts to execute the following line of code:
Dim da As New SqlDataAdapter(sql, cs)
I have been working to troubleshoot this to no avail. Thanks for any help you are kind enough to provide! Please find the additional info/code for the class below:
Imports System.Data
Imports System.Data.SqlClient
Public Class DButil
Public cs As String
Public Function GetDataView(ByVal sql As String) As DataView
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sql, cs)
da.Fill(ds)
Dim dv As New DataView(ds.Tables(0))
Return dv
End Function
Public Sub New()
cs = "Data Source=(LocalDB)\v11.0"
cs += "Data Source=(LocalDB)'C:\Users\Sean\Documents\Visual Studio 2013\Projects\349591\349591\cms.mdf';Integrated Security=True;"
cs += "Integrated Security =True;Connect Timeout=30"
End Sub
End Class
Thanks for the reply, Steve. That removed the error from the following line: Dim da As New SqlDataAdapter(sql, cs). An error now appears on the following line: da.Fill(ds). This error says SqlException unhandled, and that an expression of non-boolean type where a condition is expected near ",". Thoughts? –
Your connection string is really wrong.
For Sql Server 2012 with LocalDB instance you need
Public Sub New()
cs = "Server=(LocalDB)\v11.0;"
cs += "Integrated Security=True;"
cs += "AttachDbFileName=C:\Users\Sean\Documents\Visual Studio 2013\Projects\349591\349591\cms.mdf;"
End Sub
See examples of connectionstrings for Sql Server at connectionstrings.com
Your connection string is definitely wrong. Have a look at http://www.connectionstrings.com/sqlconnection/localdb-automatic-instance-with-specific-data-file/
Here is an example of how to query your database and return a dataview
Public Function GetDataView(sql As String) As DataView
Dim cs = "Server=(localdb)\v11.0;Integrated Security=true;AttachDbFileName=C:\Users\Sean\Documents\Visual Studio 2013\Projects\349591\349591\cms.mdf;"
Using cnn As New SqlConnection(cs)
Using cmd As New SqlCommand(sql, cnn)
Try
cnn.Open()
Dim t As New DataTable
t.Load(cmd.ExecuteReader)
Return New DataView(t)
Catch ex As Exception
''handle the error
End Try
End Using
End Using
End Function

Resources