Unable to make SQL Client Connection tp SQL Server - c#

I'm using Xamarin to connect to SQL Server while making a mobile application. The application runs on iOS. I am using sql client to establish a connection with the server, but I'm running into weird errors and have exhausted most of my options.
Please do not warn me about security issues of direct connections. This is not the concern.
The error I'm receiving is this: provider: tcp provider, error: 40 - could not open a connection to sql server)
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Data;
using System.Data.SqlClient;
namespace EmployeeSnapshot
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
void Button_Clicked(System.Object sender, System.EventArgs e)
{
var EmployeeID = UserInput.Text;
Console.WriteLine(EmployeeID);
string con = "Data Source ={Server}; Initial Catalog ={database}; Integrated Security = False; User ID ={username}; Password ={password}";
string matchingPerson;
using (SqlConnection connection = new SqlConnection(con))
{
string oString = "SELECT something FROM table WHERE employeeid = #employeeID";
SqlCommand command = new SqlCommand(oString, connection);
command.Parameters.AddWithValue("#employeeID", EmployeeID);
connection.Open();
Console.WriteLine("State: {0}", connection.State);
using (SqlDataReader reader = command.ExecuteReader())
{
matchingPerson = reader["name"].ToString();
}
command.Connection.Close();
}
Console.WriteLine(matchingPerson);
}
}
}
The code errors out at the Connection.open() line.
What I've tried:
changed the connection string around, messed with integrated security, ensured the servers are up and running, etc.
I am making this app on a MacBook. I have parallels, so I can use a virtual machine to go into windows. I decided to take advantage of this, and copied my connection string and pasted it into visual studio on the windows side. I performed a basic select statement and retrieved the data no problem, so the connection string doesn't seem to be the issue.
I almost feel like it has something to do with Xamarin or with the fact I'm on a MacBook.

I was right - the problem was with Xamarin/The visual studio project itself. All I did was clean and rebuild the solution to get everything to work. Xamarin is buggy and when in doubt, from this experience, I have learned to clean and rebuild when libraries aren't acting as expected.

Related

Making SQL queries with C# in ASP.NET

I wanted to make a controller in an ASP.NET project that executes a query to a local db (I am using SQL Server From Visual Studio).
The code is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
public class EsempiController : ApiController
{
[Route ("api/Esempi/Ruoli")]
[HttpGet]
public void GetRuoli()
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Integrated Security=True;AttachDbFilename=C:\Users\Pippo\AppData\Local\Microsoft\Microsoft SQLServer Local DB\Instances\MSSQLLocalDB\TestDB.mdf;Connect Timeout=30;TrustServerCertificate = False";
string query = "SELECT Ruoli FROM [dbo].Ruoli ";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
}
}
}
When I try to execute the code and searching on: localhost:44363/api/Esempi/Ruoli I get the following error:
System.Data.SqlClient.SqlException: 'An attempt to attach an auto-named database for file C:\Users\Pippo\AppData\Local\Microsoft\Microsoft SQLServer Local DB\Instances\MSSQLLocalDB\TestDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'
This error is showed when the line connection.Open() is executed.
I have already seen other similar problems here but I can't figure it out...
Thanks for the help
PS: I'm using VS 2019 if this can help to undestand.
You can use this site to help you configure you connection string.
An connection string example I am using to do the same thing is:
"Server= localhost; Database= [TABLE_NAME]; Integrated Security=True;"

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Evening all,
I'm trying to connect to a SQL Server 2012 database from C#. My connection settings when using SQL Server Management Studio are as below:-
Server Type: Database Engine
Server Name: Paul-PC\SQLEXPRESS
Authentication: Windows Authentication
Username: Greyed out
Password: Greyed out
The name of the database I'm trying to connect to is "testDB".
Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DatabaseConnection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30");
try
{
myConnection.Open();
MessageBox.Show("Well done!");
}
catch(SqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
}
}
}
Unfortunately, my code fails to connect with the following error:-
"You failed!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."
Any suggestions? SQL Server is running locally.
In your connection string replace server=localhost with "server = Paul-PC\\SQLEXPRESS;"
I tested all the answers here, but for me, none worked. So I studied a bit the problem, and finally I found the connection string needed. To get this string, you do:
1. in you project name:
a. right click the project name,
b. click Add,
c. select SQL Server Database (obviously you can rename it as you wish).
Now the new desired database will be added to your project.
2. The database is visible in the Server Explorer window.
3. Left click the database name in the Server Explorer window; now check the Solution Explorer window, and you will find the "Connection String", along side with Provider, State, Type, Version.
4. Copy the connection string provided, and put it in the Page_Load method:
string source = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();
I renamed my database as Product. Also, in the "AttachDbFilename", you must replace "c:\x\x\documents\" with your path to the phisical address of the .mdf file.
It worked for me, but I must mention this method works for VS2012 and VS2013. Don't know about other versions.
Try:
SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");
Replacing server=localhost with server=.\SQLEXPRESS might do the job.
Note to under
connetionString =#"server=XXX;Trusted_Connection=yes;database=yourDB;";
Note: XXX = . OR .\SQLEXPRESS OR .\MSSQLSERVER OR (local)\SQLEXPRESS OR (localdb)\v11.0 &...
you can replace 'server' with 'Data Source'
too you can replace 'database' with 'Initial Catalog'
Sample:
connetionString =#"server=.\SQLEXPRESS;Trusted_Connection=yes;Initial Catalog=books;";
use this style
#"server=.\sqlexpress;"

Connecting C# to SQL Server Compact database

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.

Connection to sql server express with visual studio 2010

I'm new to .net and c# and want to connect Sql server express available in visual studio 2010.
I have searched a lot and read connection strings in connectionstrings.com but still don't know how to connect.
i added a "service-based database" with adding new item and now have a db.mdf with tables.
my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class First
{
static void Main()
{
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=db2.mdf;Integrated Security=True");
con.Open();
Console.WriteLine("ok");
Console.ReadLine();
}
}
}
but it does not connect. in fact it executes with no errors , but no output for Console.WriteLine("ok");
how should be the connection-string in my case? specially for "Data source". I don't know what should its value be. please tell me the full connection-string which suits my case.
I'm really new to .net and confused many days for a simple connection.
also tried many other connection strings , but not working...
try with this code
using(var connection = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db2.mdf;Integrated Security=True;User Instance=True")
{
}

Problems connecting to a local MySQL database using C# and .NET 2.0

Newb questions incoming.
I'm running MySQL locally and I am having a really hard time connecting to it with C#.
Here's the code I'm using, much of the stuff I've tried out is commented out:
using System;
using System.Collections.Generic;
//using System.Data.Common.DbConnection;
using System.Threading;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Threading;
namespace mvpde
{
class Program
{
class DataReader_SQL
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
OleDbConnection con = new OleDbConnection(#"Provider=sqloledb;Data Source=127.0.0.1:3306;database=database_name;User id=id;Password=password;");
con.Open();
//Thread.Sleep(9999);
//SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//builder.DataSource = "localhost";
//builder.UserID = "hello";
//builder.Password = "password";
//builder.InitialCatalog = "db_123";
//SqlConnection thisConnection = new SqlConnection(builder.ToString());
//thisConnection.Open();
//SqlCommand thisCommand = thisConnection.CreateCommand();
//thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
//SqlDataReader thisReader = thisCommand.ExecuteReader();
//while (thisReader.Read())
//{
// Console.WriteLine("\t{0}\t{1}", thisReader["CustomerID"], thisReader["CompanyName"]);
//}
//thisReader.Close();
//thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
Thread.Sleep(9999999);
}
}
}
}
}
I've copied it nearly verbatim and tried to make it work from this site.
I have installed the MySQL on Windows 7 - I have created the user and the database I'm trying to access and I can do all this just fine using MySQL's own MySQL Workbench 5.2 CE software. I seem to have no clue what I'm doing using C# to connect to it.
All I want is to connect to it and send it a simple query like "USE DATABASE somedb" and then "SELECT TABLE sometable".
Errors I'm getting:
At first (when I used WAMP, before installing the MySQL package from mysql website) I would be able to connect once and see a login error; after that, it's as if the connection wasn't closed properly and I'd be unable to get even that far)
Now that I'm trying to connect to a MySQL instance that is created by MySQL's own software (or by running mysqld.exe) all I ever get is timeout problems\server not found\inaccessible.
Questions:
Am I using the wrong class?
What's the deal with "Provider="? where is the list of all the available variables for that part of the string? What does it mean? Why are the names involved so cryptic?
I imagined connecting to a locally-running MySQL server should be a breeze, but I've no idea what I'm doing.
Thank you.
You should use the MySql/Connector for DotNet.
Download it at this address then change your connection string accordingly.
For example "Server=127.0.0.1;Database=database_name;Uid=id;Pwd=password;Port=3306"
For other options, specific for MySQL, look at www.connectionstrings.com
have you had a look at http://www.connectionstrings.com/mysql ?
You can't use a SQL Connection object. You need a MySQL Connection object which is available in this library.http://www.connectionstrings.com/mysql
Download the MySQL Connection Library and use one of their connection strings provided on the site.
using MySql.Data.MySqlClient;
MySqlConnection myConnection = new MySqlConnection;();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
myConnection.Close();
Then use the connection object to initalise the connection string and connect to MySQL

Categories