Database Connectivity and setup of the application with the database - database

Connection string to connect the SQLSERVER Express Database and How to take setup of that database with my application.....

The following snippet should get you started .
SQLConnectionStringBuilder bldr = new SQLConnectionStringBuilder
bldr.DataSource = "Server" //Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.InitialCatalog = "MyDB" //The database on the server that you want to connect to.
bldr.UserID = "SomeUser" //The user id
bldr.Password = "SomePassword" //The pwd for said user account
SQLConnection myConnection = new SQLConnection(bldr.ConnectionString)

Related

Connect to a Microsoft SQL Server database to which is normally connected to via GlobalProtect using .NET 6 application

I'm using .NET 6, Azure Function version 4 and SqlClient in my Azure Function application.
I have a connection string like this
Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;
Normally, I access this database using GlobalProtect by providing it portal, username and password.
Now, I'm developing an Azure Function app which will access this database, but I'm getting this error
System.Private.CoreLib: Exception while executing function:
MyAzurefunction. Core .Net SqlClient Data Provider: Cannot open
server 'serverName' requested by the login. Client with IP address
'MyIpAddress' is not allowed to access the server. To enable
access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule
for this IP address or address range. It may take up to five minutes
for this change to take effect.
I know I'm getting this error because my IP Address doesn't have access to the server but how can I connect to it via my Connection String?
I create azure SQL database. connection string of database:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Image for reference:
I created function app with .net 6 in visual studio.
Image for reference:
I published it to Azure.
Image for reference:
Selected the ellipse(...) on the published page and selected Manage Azure App Service settings.
Image for reference:
Click on Add Setting in Application page and add the name of setting.
Image for reference:
In sql_connection enter the connection string of sql db in Local section for remote section click on Insert Value from Local.
Image for reference:
Install System.Data.SqlClient package in Manage Nuget packages of project. I added below code that connects to SQL Database :
using System.Data.SqlClient;
using System.Threading.Tasks;
[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
// Get the connection string from app settings and use it to create a connection.
var str = Environment.GetEnvironmentVariable("sqldb_connection");
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "UPDATE SalesLT.SalesOrderHeader " +
"SET [Status] = 5 WHERE ShipDate < GetDate();";
using (SqlCommand cmd = new SqlCommand(text, conn))
{
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
Above function runs every 15 seconds to update the Status column based on the ship date.
I added my IP address in database firewall settings.
Image for reference:
At 15 seconds after startup, the function runs.
Output of number of rows updated in the SalesOrderHeader table:
In this way I connected to my SQL database to my function app.

strange azure sql database connection issue

I got some rather strange sql database connection issue.
We have a VM that is hosted on azure and installed sql server on it.
Randomly it throws
could not open a connection to SQL Server(53)
However, the exception was not thrown fromconn.Open(), but from the place I read the Sql Data reader. The problem will last like 5-10 minutes and then disappear for every long time (e.g. days).
using (SqlConnection conn = new SqlConnection(this.ConnStr))
{
conn.Open();
InsrumentName insrument = new InsrumentName();
using (SqlCommand cmd = new SqlCommand("WF_CHART_GETNAME", conn))
{
SqlParameter para = new SqlParameter("#code", SqlDbType.VarChar, 500);
para.Value = code;
cmd.Parameters.Add(para);
cmd.CommandType = CommandType.StoredProcedure;
var reader = cmd.ExecuteReader();
while (reader.Read()) --------------- Could not open a connection to SQL Server 53 thrown here
{
Do something
}
return insrument;
}
}
I had a look of the VM and sql server log, but couldn't find anything remotely close. Anyone gets some idea?
When a pooled connection is reused, the connection error won't be raised until a query is executed on the connection. Open just returns an unused connection from the pool.
Error 53 (gleaned from the command NET HELPMSG 53) is "The network path was not found." That suggests a name resolution error which seems to be intermittent in your case.
Next time this happens, try to PING the server from the client using the same name as specified in the connection string.

WPF application database connect with remote database

I am creating a WPF application and there are two databases, one is on client computer and the other one is on a remote server. And my client asks me to sync these two databases. He asked me when my WPF application connects to the internet, it should sync local data to the remote server, and if not connected to the internet, then it should save data locally.
Tell me is there a way to connect local and remote server, can WPF access two different databases on two different computers via internet
This basically boils down to using two different connection strings where you need them (either via ADO or EF or however you're accessing your data).
void doStuff() {
using (SqlConnection conn = new SqlConnection("your first connection string here"))
using (SqlCommand cmd = new SqlCommand) {
cmd.Connection = conn;
// do stuff with command
}
using (SqlConnection conn = new SqlConnection("your second connection string here"))
using (SqlCommand cmd = new SqlCommand) {
cmd.Connection = conn;
// do stuff with command
}
}
To access the remote database, you need the correct credentials, connection string, and the remote db must allow incoming connections. Your client should have details.
For a more configuration-based approach, you might do something like this:
<connectionStrings>
<add name="LocalConnection" connectionString="your first connection string here" />
<add name="RemoteConnection" connectionString="your second connection string here" />
</connectionStrings>
and use it like so:
string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString;
Or wire those up to your entity framework/ORM classess accordingly.

How to connect local SQL server database using Google JDBC

I have a question here. I want to set up a Google sheet and populate this sheet with numbers from my local database. And my network is VPN network. I program in Google spreadsheet script editor. Using the following code to connect my local database:
var address = '10.0.0.71:1433/DatabaseName';
var username = 'DOMAIN\username';
var password = 'root';
var dbUrl = 'jdbc:sqlserver://' + address;
function createDatabase() {
var conn = Jdbc.getConnection(dbUrl, username, password);
var stmt = conn.createStatement();
var rs = stmt.execute('SELECT * FROM ITEM');
stmt.close();
conn.close();
}
However, this connection test doesn't work at all.
The error is:
Failed to establish a database connection. Check connection string, username and password.
From my understanding of Google Apps Scripts, your database need to be reachable from the Internet (that's how Google works, in the Cloud).

Duplicate SQL Server database on same server cannot be accessed

I am using SQL Server Workgroup Edition on Windows Server 2003 R2
My classic ASP pages access my production database using a system DSN. All working here.
Code like this...
<%
dbName= "ProdDB"
userID = "PublicUser"
pwd = "PublicUserPW"
Set objConn = Server.createObject("ADODB.Connection")
objConn.connectionString = "DSN=MySystemDSN"
objConn.open dbName, userID, pwd
%>
For development and testing, I created a copy of ProdDB in Enterprise Manager by
Backing up ProdDB
Restoring from the ProdDB backup set to a new database called TestDB
My understanding was that the restored database would contain an exact copy of the data as well as users, roles etc. Comparing both databases in Enterprise Manager seemed to back up this assumption.
So... I assumed I can access the test copy using the same credentials and only change the dbName, like so...
<%
dbName= "TestDB"
userID = "PublicUser"
pwd = "PublicUserPW"
Set objConn = Server.createObject("ADODB.Connection")
objConn.connectionString = "DSN=MySystemDSN"
objConn.open dbName, userID, pwd
%>
However, now my page returns
[Microsoft][ODBC Driver Manager] Data
source name not found and no default
driver specified
I have even tried creating a new System DSN, with a default database pointing at TestDB. Still no joy.
I'm sure I'm doing something simple and silly. Any assistance gratefully received.
The documentation for the open method says it's declared:
connection.Open ConnectionString, UserID, Password, Options
So it looks like you're passing in TestDB as the connection string. I usually call open without specifying any arguments. Grab a connection string from connectionstrings dot com, and:
objConn.ConnectionString = "Data Source=localhost;Initial Catalog=testdb;" & _
"User Id=myUsername;Password=myPassword;"
objConn.Open

Resources