I have published my website http://www.theyuvaworld.com for my college project but it is showing
Error 26 - Error Locating Server/Instance Specified. Other things are working properly.
You can visit website for detailed Error.
My project is C# ASP.NET 4.0 and built in Sql Server 2008 of Visual Studio 2010.
I am using this connection string in every page.
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
I know I can put it in Web.config but I don't know how to use it in aspx pages for queries?
My Question is : What changes should I do in my Connection String to get my website working.
Other details : I have taken my Web Hosting Plan from http://www.hostingfarms.in and it supports Sql Server 2008.
Try to work around this piece of code .Username and password should be supplied in get connection string if you are using sql authentication
private static void OpenSqlConnection()
{
string connectionString = GetConnectionString();
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
}
}
static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=MSSQL1;Initial Catalog=AdventureWorks;"
+ "Integrated Security=true;";
}
Related
I want to connect to SQL Server 2016 using Windows authentication.
I am using C# with this connection string
Server=192.168.1.12,14331;Database=master;Integrated Security=true;Timeout=30
or
Server=serversql\newinstance;Database=master;Integrated Security=true;Timeout=30
The error is a timeout connection.
When using connection with SQL Server authentication like this:
Server=192.168.1.12,14331;Database=master;User Id=***;Password=****;Timeout=30
everything is ok.
Source code C#
var constr = "<connection string>";
using (var connection = new SqlConnection(constr))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT 1";
command.CommandTimeout = 0;
connection.Open();
command.ExecuteNonQuery();
}
But when I am using SQL Server Management Studio to check connection to the SQL Server instance with Windows authentication, it is ok. Using alias or Ip address does not help the error.
I don't understand why I get this error ...
Help me please! Thanks you everyone!
UPDATE:
If I use connection 1 with IP and port, there is an error:
Login failed. The login is from an untrusted domain and cannot be used
with Windows
UPDATE:
Instance SQL installed on other PC the same network LAN with My PC.
I'm checked Log Viewer on PC install instance SQL but no record log.
I'm not sure it works for you, but you can try it:
SqlConnection cnn;
public connect(){
string strConnect = #"Data Source=192.168.1.12,14331;Network Library=DBMSSOCN;Initial Catalog=master;User ID=****;Password=*****";
cnn = new SqlConnection(strConnect);
try
{
cnn.Open();
}
catch(Exception)
{
// connect failed
}
}
public void ExeQuery(string query){
// query="select * from tblA"
SqlCommand sqlCmd = new SqlCommand(query,cnn);
sqlCmd.ExecuteNonQuery();
sql.Dispose();
}
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'm trying to make is so my program can have a local database after i have published it. Now i want it to work so i can install in on any computer so i have to change my connection string but i can't seem to figure out to what to change it to this is my connection string i have now
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Barcode\\Application Files\\Barcode Scanning_1_0_0_0\\BarcodeDB.mdf\"; Integrated Security = True";
Before publishing i have went into applicationfiles and made sure that BarcodeDB.mdf is included but from what i've seen it changes to BarcodeDB.mdf.deploy after i've published it.
I've also went into Prerquisites and added
SQL Server 2012 Express LocalDB
When i try to run the published program or the debugger with the code i have now i get the error:
An attempt to attach an auto-named database for file C:\Barcode\Application Files\Barcode Scanning_1_0_0_0\BarcodeDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share
I'm guessing i need to use:
| DataDirectory |
But i'm new to all of this so i can't seem to figure it out how to use it even after searching for it so i would deeply appreciate it if someone could be kind to eiter explain how i chould be using DataDirectory or if i'm wrong and should be using something else.
And also sorry if i structured this question badly trying to get better at it
Best Regards Hannes.
Edit 1: Here is the code where i try to connect and using the database
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\\Application Files\\Barcode Scanning_1_0_0_0\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products ORDER BY EDate;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
cbxProducts.Sorted = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Ok I assume that your project is a Windows Forms or WPF project if it's not please tell me.
Your problem is that you are hard-coding a path to a database file which may not exist or your process can't have access to it's location. What you have found as | DataDirectory | is to use in web projects Web.Config file which will be mapped to App_Data folder.
In your case you have to build the connection string using your own applications executable path. Try this code:
//WPF:
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{System.Reflection.Assembly.GetExecutingAssembly().Location}\\BarcodeDB.mdf\"; Integrated Security = True";
//Windows Forms:
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\\BarcodeDB.mdf\"; Integrated Security = True";
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" + Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
This fixed it for me
I'm using the following to retrieve data from a database but the SqlConnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
protected void Page_Load(object sender, EventArgs e) {
SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
I'm using this link https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx as one of my references. I'm also using SQL Server 2008 R2 Express if these information are of any help.
Here's part of the error message:
SqlException (0x80131904): Cannot open database "populate" requested
by the login. The login failed.
Any help would be greatly appreciated.
Quoted from https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse, if you want to use .mdf file as a database, you should use the following connection string containing AttacheDbFileName.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.
I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.
This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}
When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.
The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.