I'm still working on my messenger programme, it will be more secure but I'm just testing stuff. I've got a login form which is meant to connect to the SQL database, I've set it up now with a local SQL as I was trying to get it working (it still doesn't work) and I was just wondering what I did wrong.
private void button1_Click(object sender, EventArgs e)
{
LoginInfo.un = textBox1.Text;
LoginInfo.pw = textBox2.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost:3306; User Id=PXgamer;Password=Password1; Initial Catalog=login;";
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show("Error with the database connection");
}
string qry1 = "Select * from login where Password=#Password and Username=#Username";
SqlCommand com = new SqlCommand(qry1, con);
com.Parameters.AddWithValue("#Username", LoginInfo.un);
com.Parameters.AddWithValue("#Password", LoginInfo.pw);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful", "Login Information");
}
}
if (dr.HasRows == false)
{
MessageBox.Show("Access Denied", "Login Information");
}
this.Hide();
var frmMain = new frmMain();
frmMain.Closed += (s, args) => this.Close();
frmMain.Show();
}
So that's my code, the connection hangs at first, and then the "Error with the database connection" error appears. I tried looking that up, but it says it's when the connection hasn't opened. So obviously I'm guessing it's something wrong with the connection string.
In debugging, this is the part that gets highlighted:
SqlDataReader dr = com.ExecuteReader();
This is the error shown:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Error without the catch:
Additional information: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
You are trying to connect to a MySQL database using SQL Server-specific ADO.NET classes. That won't work.
You can see that your current code is trying to connect to a SQL Server instance from the error message that you got:
Additional information: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
You need to download the MySQL-specific drivers to connect to MySQL, and use that instead.
ADO.NET driver for MySQL
Losing the port (:3306) from your connection string should work fine. If the SQL Server is not on default port, specify as below (using a comma, not a colon)
Data Source=server.ip.address,1433; Initial Catalog=myDataBase;
User ID=myUsername; Password=myPassword;
Check this link for other variations of SQL Server connection strings
Every line of code that need the 'con' object to work should stay inside the 'try' block of your method.
Also, if you can't open the connection, there are two possibilities:
your connection string is wrong;
your local SQL Server doesn't accept a connection from your application (misconfigured, not running, etc);
both;
You can have a look here for connection strings for SQL Server: https://www.connectionstrings.com/sql-server-2008/
Finally... use a 'finally' block at the end for 'con.Close()'.
Related
My problem is that I can't connect to my website remote MySQL server. I have read all answers in stackoverflow.com, but I can't find right answer. Here's my C# code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
SqlConnection con;
string connectionString = #"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";
con = new SqlConnection(connectionString);
try
{
con.Open();
Console.WriteLine ("Connection Open ! ");
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
Console.WriteLine(ex.Message); //shows what error actually occurs
}
Console.ReadLine();
}
}
}
Error:
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: Named Pipes Provider, error: 40
Could not open a connection to SQL Server)
Any ideas?
When connecting to a MySQL-Database I always used the MySQL Connector you can get here: https://dev.mysql.com/downloads/connector/net/6.9.html
You have to import the MySQL namespaces to your project and then you can use the MySQLConnection instead of the SQLConnection that is, as far as I know, only for MSSQL servers.
http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp
try the following
string connectionString = #"Server=[IP adress]:3306;Database=[database];Uid=[user];Pwd=[pass];";
instead of
string connectionString = #"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";
I am trying to hit a remote Sybase database using ODBC. I have written a C# program with the following code
try
{
String conString = "Driver={Adaptive Server Enterprise};server=ipAddress;port=portNumber;db=databaseName;uid=strUserName;pwd=strPassword";
con = new OdbcConnection(conString);
con.Open();
}
catch (Exception exp)
{
con = null;
}
After the connection times out ,the exception message says :-
ERROR [08001] [Sybase][ODBC Driver]Client unable to establish a connection
On Debugging the code when I hover on "con.Open()", the ServerVersion attribute of the connection object displays the following message 'con.ServerVersion' threw an exception type 'System.InvalidOperationException'
Can anybody help me in finding out the reason for this exception..?
I would double check first that you can connect via a normal SQL client (e.g. isql, Aqua etc) on the same hostname and port.
However that looks from a quick google like a possible Sybase Adaptive Anywhere (as opposed to Enterprise) error so are you using the right driver for the type of database? They are two different products.
So I'm following this tutorial: http://support.microsoft.com/kb/314145/
and I get an unexpected error: A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
My class looks like this:
class Database
{
public Database()
{
string connectionString = "Password=pass;User ID=userid;Initial Catalog=soksko;Data Source=(local)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
Console.WriteLine("Database: OK");
}
}
I googled, but I couldnt find anything valuable. I am using MySQL database, it is on the same computer and I am using VS 2013. I successfully added my database to Server Explorer with the same connection information that I use above, but I get exception, when I try to open the connection.
See this link for how a MySQL connection string should look:
ASP.NET use SqlConnection Connect Mysql
See this link for an explanation of the oft mis-used Data Source=(local):
http://blogs.msdn.com/b/sql_protocols/archive/2008/09/19/understanding-data-source-local-in-sql-server-connection-strings.aspx
hint you're not using SQL-Server so it won't work for you
SqlConnection is for MS SQL Server. For MySql you need to use a MySqlConnection class provided by the MySQL connector (http://dev.mysql.com/doc/connector-net/en/index.html)
using MySql.Data.MySqlClient;
using(MySqlConnection myConnection = new MySqlConnection(myConnectionString))
{
myConnection.Open();
// execute queries, etc
}
The tutorial you're using is for Sql Server, not MySQL.
Hi I'm trying to connect an SQL server compact database to my program and I want a button that deletes all entries from the database, when I Press said button the program throws an exception and gives the following error message "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)"
Help Please? =]
Sorry, Code is Below =]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
namespace Booking_system_Final
{
public partial class PendingJobs : Form
{
SqlConnection sc = new SqlConnection("Data Source=C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf");
public PendingJobs()
{
InitializeComponent();
}
private void PendingJobs_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bMSDataSet.Bookings' table. You can move, or remove it, as needed.
this.bookingsTableAdapter.Fill(this.bMSDataSet.Bookings);
// TODO: This line of code loads data into the 'bMS_DataDataSet1.Bookings' table. You can move, or remove it, as needed.
}
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM Bookings");
cmd.Connection = sc;
cmd.ExecuteNonQuery();
sc.Close();
MessageBox.Show("Database Cleared");
}
}
}
Try use SqlCeConnection class rather than SqlConnection:
SqlCeConnection sqlConnection1 = new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Administrator\\My Documents\\BMS_Data.sdf;Persist Security Info=False";
If you want to connect to SQL Server Compact, use SqlCeConnection, SqlCeCommand etc. Add a reference to the SQL Server Compact ADO.NET provider, System.Data.SqlServerCe.dll
Have a look at this blog article: SQL SERVER – FIX : ERROR : (provider: Named Pipes Provider, error: 40 – Could not open a connection to SQL Server)
This goes step-by-step through what you might need to do:
In short:
SQL Server should be up and running.
Enable TCP/IP in SQL Server Configuration
Open Port in Windows Firewall
Enable Remote Connection
Enable SQL Server Browser Service
Create exception of sqlbrowser.exe in Firewall
Recreate Alias
About the where and what to do in each step, you will find more in-depth information in the article.
You may also want to have a look at the Connection strings for SQL Server Compact. There you can find other variations of the connection string you could try to play with.
You seems to be using a bad connection string. (Or the file path is wrong). Check out http://www.connectionstrings.com/sql-server-ce for connection string options.
I have database in file C:\Users\Pawel\Documents\DB.sdf. How can I connect to it?
Simple code below does not work and generates exception.
Code:
[WebMethod]
public String TestCon()
{
SqlConnection sql = new System.Data.SqlClient.SqlConnection(
#"Data Source=C:\Users\Pawel\Documents\DB.sdf");
string str = "OK";
try
{
sql.Open();
sql.Close();
}
catch (Exception ex)
{
str = ex.Message;
}
return str;
}
Result:
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)
What am I missing? What I should do to open connection correctly?
EDIT:
System.NotSupportedException: SQL Server Compact is not intended for ASP.NET development.
Great :P
Consider using System.Data.SqlServerCe.SqlCeConnection:
System.Data.SqlServerCe.SqlCeConnection con =
new System.Data.SqlServerCe.SqlCeConnection(#"Data Source=C:\Users\Pawel\Documents\DB.sdf");
(Add a reference to System.Data.SqlServerCe, if necessary)
Also, to use it with ASP.NET, add:
AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
Apparently, you are using a SQL Compact Edition (sdf file). Have you tried using SqlCeConnection instead of SqlConnection ?
As a bonus: if you dont want to mess with connectionstrings anymore, please try this.
Do do so, you have to add a reference to System.Data.SqlServerCe assembly.