connection string without server name - winforms

I am developing a c# application with sql server express database that should be run in a local network. I want to make a setup for my project by InstallAware.
I want to know how to set connection string for clients while I don't know the server name, in the other hand I want to connect to database only knowing InstanceName.
ConnectionString = #"Data Source=ServerName\InstanceName;Initial Catalog=Accounting;Persist Security Info=True;User ID=sa;Password=password";

public static string GetServerName()
{
// https://msdn.microsoft.com/en-us/library/a6t1z9x2%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();
DataRow[] dr = dt.Select("InstanceName='myInstanceName'");
if (dr.Length == 0)
return null;
return dr[0]["ServerName"].ToString();
}

Related

Getting error while trying to connect to SQL Server Analysis Service thru ADOMD

Error:
Either the user, 'myName\user', does not have access to the 'Sample' database, or the database does not exist.
I have the Sample database in SQL Server and also sample cube in the Analysis Server, however I'm getting the error while trying to run the below code which is just for checking the connection.
AdomdConnection conn = new AdomdConnection(#"Data Source=myName\MSSQLSERVER16;Catalog=Sample");
AdomdCommand cmd = new AdomdCommand("SELECT NON EMPTY { [Measures].[Sales Count] } ON COLUMNS FROM [Sample] CELL PROPERTIES VALUE");
AdomdDataReader rdr;
int count = 0;
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
while (rdr.Read())
{
count++;
}
}
conn.Close();
Console.WriteLine("Count: " + count);
Is there anything wrong in my code? or, it is about the security/access issue. However, I have added the myNmae\user as server administrator at Security of Microsoft Analysis Server. May I get some help please.
I ve solved it, you need to add yourself/user in the Analysis Service thru property > security to get access the db. (also, another mistake was using the db of sql server in connection string instead of Analysis server db). Thanks!

Can SqlBulkCopy be used with a SQL Server Compact database?

I have a live database and a local database and I want to copy a large amount of data in my live database using (SqlClient) to my local database (SqlServerCe - SQL Server CE database). How can I do that?
Yes, I have a SqlCeBulkCopy library/Nuget package that you can use:
https://github.com/ErikEJ/sqlcebulkcopy
Sample code:
using ErikEJ.SqlCe;
private static void DoBulkCopy(bool keepNulls, IDataReader reader)
{
SqlCeBulkCopyOptions options = new SqlCeBulkCopyOptions();
if (keepNulls)
{
options = options |= SqlCeBulkCopyOptions.KeepNulls;
}
using (SqlCeBulkCopy bc = new SqlCeBulkCopy(connectionString, options))
{
bc.DestinationTableName = "tblDoctor";
bc.WriteToServer(reader);
}
}

Connecting Google App Script to SQL Server on Azure (DBaaS)

I'm trying to connect a Google Sheet to an instance of SQL Server hosted on Azure (DBaaS) using Google App Script. I keep getting an error message indicating that my connection string is invalid despite my numerous attempts at modifying the code. I can connect to this instance of SQL Server on Azure using both Microsoft SQL Server Management Studio and HeidiSQL from my local machine. Note that I have white listed everyIPp address (0.0.0.0 to 255.255.255.255) to make sure that it wasn't a firewall issue preventing me from connecting.
//var conn = Jdbc.getConnection('jdbc:sqlserver:MyDBName.database.windows.net:1433/MyDBName', 'MyDBUserName', 'MyDBPassword');
// SECOND ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net:1433;'+ 'databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword;');
// THIRD ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net/MyDBName:1433', 'MyDBUserName', 'MyDBPassword');
// FOURTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('MyDBName.database.windows.net','MyDBUserName', 'MyDBPassword');
// FIFTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net', {user:'MyDBUserName', password:'MyDBPassword'});
// SIXTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('MyDBName.database.windows.net', {user:'MyDBUserName', password:'MyDBPassword'});
// SEVENTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net:1433/MyDBName', {user:'MyDBUserName', password:'MyDBPassword'});
// EIGHT ITERATION OF CONNECTION STRING
//https://developers.google.com/apps-script/reference/jdbc/jdbc
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net/MyDBName:1433', {user:'MyDBUserName', password:'MyDBPassword'});
// NINTH ITERATION OF CONNECTION STRING - Now I'm just throwing anything at the wall and seeing what sticks!
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net/MyDBName;user=MyDBUserName;password=MyDBPassword');
// TENTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:mysql://MyDBName.database.windows.net/MyDBName:1433', {user:'MyDBUserName', password:'MyDBPassword'});
// ELEVENTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net:1433;databaseName=MyDBName','MyDBUserName','MyDBPassword');
//TWELVTH
//var conn = jdbc:sqlserver://MyDBName.database.windows.net;database=MyDBName;user=MyDBUserName;password=MyDBPassword;
// THIRTEENTH
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net;user=MyDBUserName;password=MyDBPassword;databaseName=MyDBName;');
// FOURTEENTH
//var conn = Jdbc.getConnection("jdbc:sqlserver//MyDBName.database.windows.net:1433;databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword");
// FIFTEENTH
//var conn = Jdbc.getConnection("jdbc:sqlserver://MyDBName.database.windows.net:1433;databaseName=MyDBName","MyDBUserName","MyDBPassword");
// SIXTEENTH
// http://stackoverflow.com/questions/18978380/error-when-connecting-to-mssql-server-with-google-apps-script-via-jdbc?rq=1
//var conn = Jdbc.getConnection("jdbc:sqlserver://NumericalIPAddress:1433;" + "databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword;");
// SEVENTEENTH
// same as above with one less semicolon
//var conn = Jdbc.getConnection("jdbc:sqlserver://NumericalIPAddress:1433;" + "databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword");
//EIGHTEENTH
// http://stackoverflow.com/questions/15440939/querying-sql-server-with-google-apps-script-via-jdbc
var conn = Jdbc.getConnection("jdbc:sqlserver://MyDBName.database.windows.net:1433;databaseName=MyDBName","MyDBUserName","MyDBPassword");
You can find the exact connection string you should use for your database in the portal. Click on the database in the current portal (https://manage.windowsazure.com) and you should see a section that says "Connect to your database" below that there is a link that says "View SQL Database connection strings for ADO .Net, ODBC, PHP, and JDBC.
Alternatively, if you are using the new version of the Azure portal (https://portal.azure.com), you can find the connection strings via Browse All > SQL databases > MyDBName > Show database connection strings.
The example it provides for me looks like:
jdbc:sqlserver://server21.database.windows.net:1433;database=Test;user=myuser#server21;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
I'm trying to connect to an Azure database and found that the JDBC connection string specified in the Azure portal and the sample from Google do not work as-is. The Azure one contains several properties that the script engine says are not supported and the Google one (updated from MySQL) doesn't work. Here's what I got to work:
var user = 'USER#SERVER';
var userPwd = 'PASSWORD';
var database = 'DB_NAME'
var connectionString = 'jdbc:sqlserver://SERVER.database.windows.net:1433;databaseName=' + database;
var conn = Jdbc.getConnection(connectionString , user, userPwd);
NOTE: "database=" is not supported but "databaseName=" is supported. None of the encrypt or certificate tags are supported.
Also, there is a big set of IP ranges you must add to the firewall rules on your server instance. If you use the portal to add these note that you can only make one change to the firewall rules at a time; this means add a range, save, repeat. Don't add all 10 and then get an error when trying to save them (like I did the first time). see: https://developers.google.com/apps-script/guides/jdbc
For your information, the right connection string that works(as at June 5th 2018) to create an ODBC connection between Google Apps Script and a SQL Server DB on Azure DBaaS is as follows:
var conn = Jdbc.getConnection('jdbc:sqlserver://SERVER.database.windows.net:1433;databaseName={yourDatabaseName};user={yourUsername}#{yourServer};password={yourPassword}');

Error when connecting to MSSQL Server with Google Apps Script via JDBC

I'm trying to connect to Microsoft SQL Server using Google Apps Script. I'm using SQL Server 2008 R2 and I am using one of the suggested scripts that's supposed to read data and put it into a Spreadsheet:
https://developers.google.com/apps-script/jdbc#reading_from_a_database
The error message is:
Failed to establish a database connection. Check connection string, username, and password
Username and password are OK, the user is DBowner. The port is also correct, I tried to connect to the server via Telnet using:
o IP-address 1433
and it works.
Here's the code:
function foo() {
var conn = Jdbc.getConnection("jdbc:sqlserver://IP-adress:1433/DBName","user","password");
var stmt = conn.createStatement();
stmt.setMaxRows(100);
var start = new Date();
var rs = stmt.executeQuery("select * from person");
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var row = 0;
while (rs.next()) {
for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
cell.offset(row, col).setValue(rs.getString(col + 1));
}
row++;
}
rs.close();
stmt.close();
conn.close();
var end = new Date();
Logger.log("time took: " + (end.getTime() - start.getTime()));
}
Do you have any idea of what can be wrong? Do I have to make some configuration on my Server? Or in the database? The instructions mentioned above says to ensure that Google's Ip-addresses can reach the database. But instead of listing all of Google's IP-addresses I granted access to all on that port. I also enabled TCP/IP Protocol in SQL Server Configuration Manager. And I granted "Remote connections" to the Server in MSSMS. Any other idea, please?
Well, I found the answer here:
Google Apps Scripts/JDBC/MySQL
Obviously, the connection string has to look like this:
var conn = Jdbc.getConnection("jdbc:sqlserver://IP-address:1433;" + "databaseName=DBName;user=username;password=password;");
I don't understand why connection string differs from the one in Google Documentation but this one works for me...
The Issue is in the Connection string.
It should be like so
address = '%YOUR SQL HOSTNAME%';
user = '%YOUR USE%';
userPwd = '%YOUR PW%';
dbUrl = 'jdbc:sqlserver://' + address + ':1433;databaseName=' + queryDb;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
I have an entire tool on GitHub where you are able to connect to MySQL and SQL Servers. I you will be able to use it to help you. I will be constantly updating with more features overtime! You can find it here.
GOOGLE SPREADSHEET JDBC CONNECTOR TOOL

Manually Connection between SQL Server and Model

I created a empty project in ASP.Net and then I manually add it view,controller and model. Now I want to connect SQL Server to Model class. How can I do it ?
try with this code, this code contain select query for just example
// Is your string connection to your database and server
string connectionString = ""; //connection to your database
//Create a connection to your database
//using bloc , in order to destruct connection object in the end of treatment
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Create object command who contain your query sql, permit you to get data or //insert on update or delete data
using (SqlCommand command= connection.CreateCommand())
{
//for example a query, who select data from table in your databse,
command.CommandText = "SELECT * FROM Table where col = #ParameterTest";
//for exxample a parameter for your query
command.Parameters.Add("#ParameterTest", 123); //your test value
//after create connection you must open this
command.Connection.Open();
//get data in reader, structure for readin datas
var reader = command.ExecuteDataReader();
}
}

Categories

Resources