SQL query running as local user instead of user in connection string - c#

I have a WPF application that accesses a SQL server using SqlConnection with a connection string.
private string connString =
"user id=*****;" +
"password=*****;" +
"server=1.1.1.1;" +
"Trusted_Connection = yes;" +
"database=****;" +
"connection timeout = 30";
private SqlConnection myConnection = new SqlConnection(connString);
The string contains the username and password for the account I want the program to use to access the database. This works as I would expect it to on my machine. Once I run it on another machine I get a an error:
"Login failed for user 'Domain\local user'"
I am sure that I am just missing some sort of setting or configuration.
Any help would be great

Trusted_Connection = yes tells SQL Server to use Integrated (Windows) Authentication. Your user name and password are ignored.

Related

azure connection string c#

I am trying to open connection with Azure SQL database. Tried creating usual connection = new MySqlConnection("Server=" + server + "Database=" + database + "Uid=" + uid + "Password=" + password); with every string variable ending with ; but yet it always fails to connect even if the data is correct. Tried to use given string for ADO.NET but then I am getting exception "keyword is not supported". I don't what else to actually.. Googled as much as possible but all solutions are quite the same and yet nothing works out for me :/
Firstly, azure databases don't use mysql. so using MySqlConnection() won't work.
instead use
SqlConnection connection = new SqlConnection(connectionstring);
Standard connection strings should be in the format
Server=tcp:[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;
See https://www.connectionstrings.com/azure-sql-database/ for more options
var connectionString = #"Server=tcp:<dbname>.database.windows.net,1433;Initial Catalog=<databasename>;Persist Security Info=False;User ID=<userid>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
That's how I connect to my Azure SQL Database, works for me.
For MySQL In App you can use the fellowing code in c# to get the connection string:
static string getConnectionString()
{
#if DEBUG
string connectionString = "dbname=localdb;host=localhost:3306;user=root;pass=password;";
#else
string connectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb");
#endif
string[] options = connectionString.Split(";");
string database = options[0].Split("=")[1]; ;
string serverport = options[1].Split("=")[1];
string server = serverport.Split(":")[0];
string port = serverport.Split(":")[1];
string user = options[2].Split("=")[1];
string password = options[3].Split("=")[1]; ;
connectionString = $"server={server};port={port};database={database};user={user};password={password};";
return connectionString;
}
The standard .Net Framework provider format is:
Server=[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;
Azure SQL Database is an SQL Server type database, not MySQL!
Have you followed Microsoft instructions?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-dotnet-visual-studio
You have to create server-level firewall rule on azure too, to be able to connect.

Method fires an exception when trying to connect to remote SQL Server

I want to create a simple tool that connect to SQL Server then list all databases, and after user selects one of those databases, the tool will perform some SQL scripts on it.
Below is a method that should return a DataTable contains all my databases;
I send to it sqlServerIp as first parameter like 10.10.20.30 ip address not server name.
Also I didn't specify a SQL Server instance.
private DataTable GetSqlServerDatabases(String sqlServer, bool isWindowsAuth, String login, String password)
{
String connectionString;
DataTable databases;
if (isWindowsAuth)
{
connectionString = "Data Source=" + sqlServer + ",1433;Network Library=DBMSSOCN; Integrated Security=True;";
}
else
{
connectionString = "Data Source=" + sqlServer + ",1433;Network Library=DBMSSOCN;" + "User id=" + login + ";Password=" + password + ";";
}
try
{
using (var con = new SqlConnection(connectionString))
{
con.Open();
databases = con.GetSchema("Databases");
foreach (DataRow database in databases.Rows)
{
String databaseName = database.Field<String>("database_name");
short dbID = database.Field<short>("dbid");
DateTime creationDate = database.Field<DateTime>("create_date");
}
}
}
catch(Exception ex)
{
databases = null;
MessageBox.Show(ex.Message.ToString());
}
return databases;
}
When I try to call the method on more than one server I faced an exception:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
or
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
I used connection string with Network Library=DBMSSOCN; after searching here on SO and web so I don't know what is the wrong with this method.
Remove Integrated Security parameter. This parameter is for trusted connections.
More samples on http://www.connectionstrings.com/sql-server

error "Login failed for user" C# with SQLConnection

I created a database (without user or password) as a service-based database.
Now I'm trying to insert to a database, but there is a error "Login failed for user"
I have this code:
string J_connetionString1 = null;
SqlConnection J_connection1;
SqlDataAdapter J_adapter1 = new SqlDataAdapter();
string J_sql1 = null;
J_connetionString1 = #"Data Source=.\SQLEXPRESS;Initial Catalog=J_InsData";
J_connection1 = new SqlConnection(J_connetionString1);
J_sql1 = "update instinfo set instinfoNAME = textBox2.text where instinfoID ='1'";
try
{
J_connection1.Open();
J_adapter1.UpdateCommand = J_connection1.CreateCommand();
J_adapter1.UpdateCommand.CommandText = J_sql1;
J_adapter1.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Row updated !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
i can't comment so i edited the Q.
this error appeared by using this code
error :
system.Data.sqlclint.sqlexpection(0x80131904)
cannot open database "J_InsData" request by the login. the login faild
login failed for user J-PC\J
code:
J_connetionString1 = #"Data Source=.\SQLEXPRESS;Initial Catalog=J_InsData;Trusted_Connection=True;Integrated Security=SSPI";
You need to tell SQL Server which user credentials to use for a connection.
Hence you should provide a user id and password of SQL Server user in your connection string.
Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;
On the other hand if the SQL erver is configured to accept windows domain users, you can use Integrated Security=SSPI or Trusted_Connection=True in the connection string.
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Server=myServerAddress;Database=myDataBase;Integrated Security=SSPI;
Have you tried adding the following to your connection string?
Integrated Security=True
or
Integrated Security=SSPI
which is pretty mcuh the same as True.
This LINK might be useful for you as well.

No start database manager command was issued error

I have a DB2 expresss in my machine and I am able to query from the database using command window (after following two commands):
set DB2INSTANCE=db2inst1
db2 connect to tims user
Now, when I try to connect to the database from a C# console application, I am getting following errors with different connection strings.
Attempt 1
string connectionString = #"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; CurrentSchema=db2inst1; ";
SQL1032N No start database manager command was issued. SQLSTATE=57019
Attempt 2
string connectionString = #"Provider = IBMDADB2; Database = TIMS; CurrentSchema=db2inst1; ";
SQL1031N The database directory cannot be found on the indicated file system. SQLSTATE=58031
What should be the correct connection string for this scenario?
CODE
string connectionString = #"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; CurrentSchema=db2inst1; ";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = connectionString;
myConnection.Open();
Do you have multiple DB2 instances running on your machine? You can get a list of instances that exist by executing the db2ilist command.
If you have to execute the set DB2INSTANCE=db2inst1 statement when you open a DB2 Command Window in order to connect to the TIMS database with the db2 connect to TIMS command, then you need to ensure that the environment for your C# application is configured the same way.
You can do this in a number of ways:
by setting the DB2INSTANCE environment variable before starting your application
Change the default DB2 instance on your machine by using the command db2set -g DB2INSTDEF=db2inst1 (** see note below)
Use a TCPIP connection string (as described by #Bhaarat) so that your application does not depend on the database catalog for the default instance
Note: Before changing DB2INSTDEF you may want to see what the current value is, by executing the command db2set -all and looking for DB2INSTDEF in the output. Also note that changing the default instance may affect other applications that run on your machine.
refer this url http://www.c-sharpcorner.com/uploadfile/nipuntomar/connection-strings-for-ibm-db2/
your connection string should be something like this
Provider=IBMDADB2;Database=urDataBase;Hostname=urServerAddress;Protocol=TCPIP;Port=50000;
Uid=urUsername;Pwd=urPassword;
in more you can refer this too
http://www.codeproject.com/Articles/4870/Connect-to-DB2-from-Microsoft-NET
My DB2 insatnce name is "db2inst1" and it was working fine when I used DB2 command window.
Now I made following settings and it is working fine now. :-)
Created a port in the C:\Windows\System32\drivers\etc\services file (db2c_db2inst1 50010/tcp)
Set the “TCP/IP Service Name” ( = db2c_db2inst1”) for the instance. Verified using “db2 get dbm cfg” command
Updated the environment variable DB2INSTANCE with the value “db2inst1”
Restarted the machine
Started the instance
ConnectionString
"Provider = IBMDADB2; Database = TIMS; Hostname = localhost; Protocol = TCPIP; Port = 50010; Uid = myUserID; Pwd = myPassword";
CODE
string queryString = "SELECT * FROM DBATABC";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
string companyCode = reader.GetString(0).ToString();
}
}
}
reader.Close();
}
}
Note: Try to create DSN for ODBC and use ODBC connection in a sample SSIS package. This will help in resolving OLEDB connection issues also (that are common to both)

Create an SQL Express 2008 database in C# code, but login fails when trying to connect with a sysadmin

I have a piece of code that creates an SQL Server Express 2008 in runtime, and then tries to connect to it to execute a database initialization script in Transact-SQL. The code that creates the database is the following:
private void CreateDatabase()
{
using (var connection = new SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=master;" +
"Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
"CREATE DATABASE " + m_databaseFilename +
" ON PRIMARY (NAME=" + m_databaseFilename +
", FILENAME='" + this.m_basePath + m_databaseFilename + ".mdf')";
command.ExecuteNonQuery();
}
}
}
The database is created successfully. After that, I try to connect to the database to run the initialization script, by using the following code:
private void ExecuteQueryFromFile(string filename)
{
string queryContent = File.ReadAllText(m_filePath + filename);
this.m_connectionString = string.Format(
#"Server=.\SQLExpress; Integrated Security=true;Initial Catalog={0};", m_databaseFilename);
using (var connection = new SqlConnection(m_connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryContent;
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
}
}
However, the connection.Open() statement fails, throwing the following exception:
Cannot open database "TestData"
requested by the login. The login
failed. Login failed for user
'MYDOMAIN\myusername'.
I am completely puzzled by this error because the account I am trying to connect with has sysadmin privileges, which should allow me to connect any database (notice that I use a connection to the master database to create the database in the first place).
Is there a reason you specify User Instance=True when you create it but not when you try to connect to it?
When you create it after connecting with User Instance, it will create the database files but does not attach it to your actual instance. You'll either have to not specify User Instance=True in the first connection string or add it to the second and specify the database file to use.
Is the user you are logging with have rights to the database 'TestData'?
If not grant the user the privileges required.
I am not sure if this means anything, but in your first create you are connecting to server
.\\sqlexpress
The second one is
.\SQLExpress
You'll need to issue a CREATE USER command (see: http://msdn.microsoft.com/en-us/library/ms173463.aspx) after creating the database but before trying to open a connction to that database.
For example:
CREATE USER 'MYDOMAIN\myusername' FOR LOGIN 'MYDOMAIN\myusername'

Categories