I'm trying to connect to my local SQL express database with following code with no luck :
string strConnectionString = null;
SqlConnection cnn = null;
strConnectionString = "Data Source=" + txtSQLServer.Text.Trim() + ";Initial Catalog=" + txtSQLDatabase.Text.Trim() + ";User ID=user;Password=user";
cnn = new SqlConnection(strConnectionString);
MessageBox.Show(strConnectionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The sql express database is running, because I can connect with it through SQL server management studio.
I already tried "localhost", "127.0.0.1", "PC-name/SQLEXPRESS"
error says : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
What more can I try?
edit : ok, found the problem
I needed to start the SQL server browser
connect to "PC-name/SQLEXPRESS"
But in the future I want to connect to an IP-address, how do I do this?
I tried this connection string :
strConnectionString = "Data Source=" + txtSQLServer.Text.Trim() + ",1433;Network Library=DBMSSOCN; Initial Catalog=" + txtSQLDatabase.Text.Trim() + ";User ID=user;Password=user";
Related
So I've got a little (and valid) .MDF database file (SQL Server). However when I try to access it (line 32 here) or smaller context here...
private void loadDataBaseButton_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string databasePath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
//SqlConnection dataBaseConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlConnection dataBaseConnection = new SqlConnection(string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True", databasePath));
try
{
dataBaseConnection.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
However it throws an exception. Specifically it is an
Error 26 - Error Locating Server/Instance Specified
A network-related or instance-specific error occurred while establishing
a connection to SQL Server. The server was not found or was not
accessible. Verify that the instance name is correct and that SQL Server is
configured to allow remote connections. (provider: SQL Network
Interfaces, error: 26 - Error Locating Server/instance specified)
The .MDF file is valid and everything else to my knowledge seems to check out. How do I fix this?
In your code problem is Connection string.
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20180630124430.mdf;Initial Catalog=aspnet-WebApplication1-20180630124430;Integrated Security=True"
this is currect connection string if you using to attached .mdf file.
if you connecte to sql server then connection string is
data source=DHARMESH-PC;initial catalog=AdventureWorks;user id=sa;password=sa123
Hope this will help you
Thanks
Update:-
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string databasePath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
string dbname = openFileDialog1.FileName.Split('.')[0];
//SqlConnection dataBaseConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True");
string connection = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=" + databasePath + ";Initial Catalog=" + dbname + ";Integrated Security=True";
SqlConnection dataBaseConnection = new SqlConnection(connection);
try
{
dataBaseConnection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have update your code .
You have to select only MDF file .
I believe if you're trying to connect to "SQLEXPRESS" that would imply that you are running SQL Server Express locally and attaching the database
I've been able to successfully access localdb MDF files with a connection string like this:
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDBFile.mdf;Integrated Security=True" providerName="System.Data.SqlClient"
You should also verify that the file is in the expected "DataDirectory."
If you are using
User Instance=true
you must use named pipes so your connection will change from:
.\SQLEXPRESS
to
.\\SQLEXPRESS
The network protocol for user instances must be local Named Pipes. A
user instance cannot be started on a remote instance of SQL Server,
and SQL Server logins are not allowed.
sql-server-express-user-instances
I have a console app and want to connect other windows server where I have already created user, database table. In conf.xml I have
<configuration>
<crypto location="172.16.10.34" database="Crypto_Pan" username="PinbySms" password="ASDasd123"/>
</configuration>
then my code is :
Dictionary<string, string> d = conf.getCrypto();
SqlConnectionStringBuilder bu = new SqlConnectionStringBuilder();
bu.DataSource = d["location"];
bu.NetworkLibrary = "DBMSSOCN";
bu.InitialCatalog = d["database"];
bu.IntegratedSecurity = false;
bu.UserID = d["username"];
bu.Password = d["password"];
SqlConnection thisConnection = null;
try
{
thisConnection = new SqlConnection(bu.ConnectionString);
thisConnection.Open();
Console.WriteLine("success connected");
}
catch (Exception e)
{
Console.WriteLine("exeption: " + e.ToString());
thisConnection.Close();
}
I have an error when my app try to connect this database:
[System.Data.SqlClient.SqlException] = {"A network-related or
instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify
that the instance name is correct and that SQL Server is configured to
allow remote connections.
Does anybody have any suggestions?
there was not default port in sql configuration PROTOCOL MSQSQLSERVER TCP/IP , i changed it to 1433 and now it's ok.
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
i have a PHP website and MySQL database in same web sever. i wont to connect that MySQL database with c# application. my c# application in run another computer.
how can i connect that MySQL database ?
First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website. In this article, I will use the Connector/NET version 6.1.
Then add MySql.Data namespace in Reference
Then you can use mysql in .net
now create a connection strin like this
class ConnectToMySql{
private MySqlConnection connection;
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
connection.Open();
}
}
Then
1 Create a MySQL command.
2 Assign a connection and a query to the command. This can be done using the constructor
3 using the Connection and the CommandText methods in the MySqlCommand class.
4 Create a MySqlDataReader object to read the selected records/data.
5 Execute the command.
6 Read the records and display them or store them in a list.
7 Close the data reader.
8 Close the connection.
I tooth this will help full for you . now you can start working on mysql in .NET
Best of luck
you firstly have to add mysql ref to your project:
plz right click on your project and go to the ref part in it
after that try to find mysl.conncetor and tick it
and refresh your project and firstly try to add using mysql.net.client
now you can use data base located in the mysql db from c# coding
be sure you have downloaded both mysql connector and installaton which is about 500 mb files.
class ConnectToMySql{
private MySqlConnection mscon;
private void Initialize()
{
server = "localhost";
database = "your own database name";
uid = " your username";
password = "your password";
string const;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mscon= new MySqlConnection(const);
mscon.Open();
}
}
I'm connecting to a mysql database in c#, and it all works well as long as I input the server address as "localhost" or its ip, but if I try a remote ip it fails with:
Error: 0 : Unable to connect to any of the specified MySQL hosts.
here's the code:
server = Properties.Settings.Default.DBHost;
port = Properties.Settings.Default.DBPort;
database = Properties.Settings.Default.DBName ;
uid = Properties.Settings.Default.DBUser;
password = Properties.Settings.Default.DBPassword ;
string connectionString;
connectionString = "SERVER=" + server + ";" + "PORT=" + port + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
[...]
if (this.OpenConnection() == true){
// exec db operations
}
else{
MessageBox.Show("Database Connection Error.");
}
Tested:
No firewall restrictions
Same error in different computers
Already tried on with different remote databases, all with set privileges and accessible from other sources
If its your mysql server then,
Check you port is open or not. (probably 3306)
Change your bind-address in your my.ini file (from 127.0.0.1 to 0.0.0.0)
Double check the user your trying to connect to server has necessary privileges
If its not your mysql server then,
Ask the provider whether they are supporting remote connections or not.
1st you have to check if your server is supporting remote MySQL database Connection then
You can try this MySQL Connection String Builder example, i'm working with all the time .. no errors :
_connectionStr = new MySqlConnectionStringBuilder
{
Server = "127.0.0.1",
Database = myDatabase,
UserID = myUserName,
Password = myPassword,
ConnectionTimeout=60,
Port = 3306,
AllowZeroDateTime = true
};
_con = new MySqlConnection(_connectionStr.ConnectionString);
try
{
_con.Open();
}
catch
{
MessageBox.Show("Error, help i can't get connected!");
}
Hope this works!
Maybe your MySQL Server is not configured to listen to any of your IP Interface.
Maybe it is just listening into your "localhost:3306"
Check it in your MySQL Server config file "bind-address".