error 26- error locating server/instance specified - c#

I designed a C# desktop app in visual studio 2019 and for database used sql server express 2019 edition. i am trying to run this app on another pc. i have installed sql server express 2019 in the other pc also MS server management studio 2019 installed and restored the database. everything works fine like login,saving updating,deleting but when i try to fetch data to datagridview it shows "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 instance name is correct and sql server is configured to allow remote connections.(provider: sql network interfaces, error: 26 - error locating server/instance specified)."
all the ports are enabled and firewall rule is also enabled in the client pc.
i am using the below connection string for the connection.
class Connection
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=icon;Integrated Security=True");
public SqlConnection active()
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
return con;
}
}
Please help anyone as i am not able to get what is the problem going on.
Belowcode is working
private void loginBtn_Click(object sender, EventArgs e)
{
Connection con = new Connection();
SqlCommand cmd = new SqlCommand("select * from [user] where
Username='" + usernameTxt.Text + "'and password='" + passwordTxt.Text
+ "'", con.active());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
but this is not working.it shows the error when i try to fetch the data.
public partial class AllSudent : Form
{
public AllSudent()
{
InitializeComponent();
}
Connection con = new Connection();
public int studentID;
private void AllSudent_Load(object sender, EventArgs e)
{
GetStudentsRecord();
}
public void GetStudentsRecord()
{
SqlCommand cmd = new SqlCommand("Select * From [student]",
con.active());
DataTable dt = new DataTable();
SqlDataReader sdr = cmd.ExecuteReader();
dt.Load(sdr);
sdataGridView.DataSource = dt;
}

Throw your Connection class away, and pass the connection string to the DataAdapter. Don't bother opening or closing the connection; DataAdapter knows how to open a connection if it's closed
Put the connectionstring into the Settings
Use parameters
private void loginBtn_Click(object sender, EventArgs e)
{
using(var sda = new SqlDataAdapter("select * from [user] where Username=#user and password=#pass", Properties.Settings.Default.ConStr)
{
//USE PARAMETERS
sda.SelectCommand.Parameters.Add("#user", SqlDbType.VarChar, usernameTxt.Text.Length).Value = usernameTxt.Text;
sda.SelectCommand.Parameters.Add("#pass", SqlDbType.VarChar, passwordTxt.Text.Length).Value = passwordTxt.Text.GetHashcode(); //DO NOT store your passwords in plain text!!
var dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login Successful", "Sucsess",
MessageBoxButtons.OK, MessageBoxIcon.Information);
new dashboard().Show();
this.Hide();
}
}
}
Use parameters
Just in case you missed it: USE PARAMETERS. Never again, in your life ever, should you concatenate a value into an SQL string. Ever. There is no reason to do it, and doing it will result in the software you create being hacked / you getting fired / both
Also, don't store passwords in plain text, ever. Salt and hash them. I've used string.GetHashcode() for demo purposes, which is not good but better than plaintext
Do the same thing to the not working code:
public void GetStudentsRecord()
{
using(var sda = new SqlDataAdapter("Select * From [student]", Properties.Settings.Default.ConStr)){
var dt = new DataTable();
sda.Fill(dt);
sdataGridView.DataSource = dt;
}
}

this issue also confusing me a few days after the IT guy do some security settings to the SQL Server. i have an EntityFramework for the Web application and a desktop application. after i did some setting on the SQL Server, the Web application comeback to work, but the desktop still with issue. but i used the some connection string for the both application, it make no sense one is work but the other doesn't. then i searched a lot until i found some one said need add a port number 1433 after the $ServerName$DatabaseInstanceName,1433 at here http://www.windows-tech.info/15/9f6dedc097727100.php . after i added it. the exception became: System.Data.SqlClient.SqlException: Login failed for user 'domain\name-PC$'. then i found this link System.Data.SqlClient.SqlException: Login failed for user: System.Data.SqlClient.SqlException: Login failed for user it said need add Trusted_Connection=False;. the whole connection string should be like: data source=XXXXX\SQLSERVER,1433;initial catalog=XXXDB;user id=UserID;password=PWD;Trusted_Connection=False;MultipleActiveResultSets=True;
hope this answer will help the ones out off Generic exception: "Error: 26-Error Locating Server/Instance Specified)

Related

SQL Exception in Windows CE device

I'm working on Windows CE application, I was trying to connect to server database from the device and fetch some information from db on button click, below is the code I tried,
SqlConnection conn = new SqlConnection("Data Source=192.168.0.0;Initial Catalog=DashReport;Integrated Security=SSPI; User ID=SA;Password=Admin#123;");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT STORE, YEAR,DATE FROM TOPSALES WHERE MONTH = " + txtcode.Text + ";";
// cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gvDataGrid.DataSource = dt;
}
else
{
MessageBox.Show("No data found");
}
}
conn.Close();
but while running the application I'm getting a SqlException. It seems there is something wrong with the connection string. What is the right method to do it?
You cannot have both the integrated security and specify a specific user id and password at the same time. Since you have the Integrated Security=SSPI;, that will take precedence and your connection tries to connect with the currently logged in Windows user.
Most likely, from a Windows CE device, you want to use the specific User I
string connStr = "Data Source=192.168.0.0;Initial Catalog=DashReport;User ID=SA;Password=Admin#123;"
SqlConnection conn = new SqlConnection(connStr);
And another word of caution from long time SQL Server users, admins, and programmers: you should NEVER EVER use the built-in sa account! Just don't do it - use another account (possibly one you create specifically for this application).
Have you tried using the Server Explorer of Visual Studio, then connect to the database, get the Connection String via Properties Window, and use it as your connection string?
Just some kind of assurance that your connection to the database is the same as your code.

Could not find available ISAM

OleDbConnection connect = new OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data source:C:\\Users\\PC\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Firebird damagem0.accdb;Persist Security Info=False");
public partial class Form3 : Form
{
// OleDbconnection database
OleDbConnection connect = new OleDbConnection ("Provider=Microsoft.ACE.OLEDB.12.0;Data source:C:\\Users\\PC\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Firebird damagem0.accdb;Persist Security Info=False");
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Set up command
connect.Open();
OleDbConnection command = new OleDbConnection("SELECT [Damage columns], ID FROM [Copy of Firebird m0 damage]; connection");
command.ExecuteNonQuery();
DataTable ds = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter (command);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["[Damage columns]"].ToString());
}
connect.Close();
}
Error occurs at connect.Open(); I've done everything right but i still keep receiving the error, any suggestions?
This error is typically due to an invalid connection string.
Since you have a space in your datasource path, try wrapping it with single quotes. Also, it should be
Data Source=
not
Data Source:
You connection string looks to be wrong with a semicolon after Data Source.
OleDbConnection connect = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\PC\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Firebird damagem0.accdb;Persist Security Info=False");
Also you have another OleDbConnection there in code which should be OleDbCommand.
And finally, did you install the access database engine?
I just managed to produce a very similar error out of thin air (it worked before) and after a while of digging around what I changed since then I finally found the mistake:
Provider=Microsoft.Jet.OleDb.4.0;Data Source=myfile.mdb
works, while
Provider=Microsoft.Jet.OleDb.4.0;DataSource=myfile.mdb
produces
Installable ISAM not found
For those who don't see it: The difference is the spelling of the key Data Source vs DataSource - the space character is important here!

Connection to MS SQL Server from smart device

I have the trouble with connection to MS SQL Server from Smart Device Project in Visual Studio 2008.
private void button2_Click(object sender, EventArgs e)
{
string connStr = "Data Source=SERVER-5;Initial Catalog=MydB;Integrated Security=SSPI;Connection Timeout=5";
DataTable data;
using (var connection = new SqlConnection(connStr))
{
try
{
var sda = new SqlDataAdapter("select * from pri_date", connection);
var ds = new DataSet();
sda.Fill(ds);
data = ds.Tables[0];
}
catch (SqlException ex)
{
var exc = ex.InnerException;
}
}
}
I'm trying to run this code in Visual Studio and I'm getting the error "Specified SQL server not found: SERVER-5" .
When I tried to launch this code in Windows application everything worked ok.
It's highly likely that it's a name resolution issue. If you use the server's IP address instead of the name, it will likely work. If that does work, then you need to make sure you have the DNS Server properly set for your device's network adapter.

C# MS Access Database Connection System.Data.SqlClient.SqlException' occurred in System.Data.dll

I am not sure if this problem has anything to do with my code or simply the way that my database is set up. Any pointers would be awesome!
This is the error message that I get:
I have gone to "Modify Connection" and used the 'Test Connection' tool and that says that it connects fine but when the actual program runs nothing happens and I get the error.
Here is my code:
private void btnAddCustomer_Click(object sender, EventArgs e)
{
SqlConnection CustomerInfo = new SqlConnection("Data Source=C:\\Users\\Cory\\Desktop\\DeluxWrapsWindows\\DeluxWrapsWindows\\DeluxWraps_DB.mdb");
{
SqlCommand xp = new SqlCommand("Insert into CustomerInfo(LastName, FirstName, Email, PhoneNumber, Address, Instagram, CarMake, CarModel, AdditionalNotes) Values(#LastName, #Firstname, #Email, #PhoneNumber, #Address, #Instagram, #CarMake, #CarModel, #AdditionalNotes)", CustomerInfo);
xp.Parameters.AddWithValue("#LastName", txtLastName.Text);
xp.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
xp.Parameters.AddWithValue("#Email", txtEmail.Text);
xp.Parameters.AddWithValue("#PhoneNumber", txtPhoneNumber.Text);
xp.Parameters.AddWithValue("#Address", txtAddress.Text);
xp.Parameters.AddWithValue("#Instagram", txtInstagram.Text);
xp.Parameters.AddWithValue("#Carmake", txtCarMake.Text);
xp.Parameters.AddWithValue("#CarModel", txtCarModel.Text);
xp.Parameters.AddWithValue("#AdditionalNotes", txtAdditionalNotes.Text);
CustomerInfo.Open();
xp.ExecuteNonQuery();
CustomerInfo.Close();
}
}
You should try create the SqlCommand with:
SqlCommand xp = CustomerInfo.CreateCommand();
See this example:
https://msdn.microsoft.com/pt-br/library/system.data.sqlclient.sqlconnection.createcommand(v=vs.110).aspx
Update:
Try use OleDbConnection. See:
public DataSet GetDataSetFromAdapter(
DataSet dataSet, string connectionString, string queryString)
{
using (OleDbConnection connection =
new OleDbConnection(connectionString))
{
OleDbDataAdapter adapter =
new OleDbDataAdapter(queryString, connection);
// Set the parameters.
adapter.SelectCommand.Parameters.Add(
"#CategoryName", OleDbType.VarChar, 80).Value = "toasters";
adapter.SelectCommand.Parameters.Add(
"#SerialNum", OleDbType.Integer).Value = 239;
// Open the connection and fill the DataSet.
try
{
connection.Open();
adapter.Fill(dataSet);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
return dataSet;
}
See more details in: https://msdn.microsoft.com/en-us/library/System.Data.OleDb.OleDbParameterCollection(v=vs.110).aspx
It sounds like your trying to use a local database or auto-named database: Here is the syntax for your connection string:
Data Source=(LocalDB)\v11.0;
AttachDbFilename=Your local location here;
Integrated Security=True
Hope that helps.
The problem is you're using System.Data.Sql as the provider, when it should all be coming from System.Data.OleDb;
However, you can use <asp:SqlDataSource> in ASPX, to connect to an Access Database, but that is not the same thing as System.Data.Sql.

conn.open() oracleException was unhandled

I'm developing a Windows CE app in C# and trying to connect to an Oracle database. I'm using CoreLab.Oracle reference. This is my code:
using CoreLab.Oracle;
namespace SmartDeviceProject1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "User ID=name;Password=pass;Host=ip;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;Port=1522;Sid=bleh;Unicode=True";
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from dc_emp ";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
}
}
}
Every time I run the project conn.Open(); gets error : Network error:: A Socket operation was attempted to an unreachable host. So something is wrong with my connection string but I don't know what.
I might add that when I drag and drop a "oracleConnection" component to my form in design mode and edit the properties, my connection is created.
I have read in some forums I must set the "direct" property to true in my connection string, but when I add it to my connection string it says : Unknown connection string parameter Direct
Can someone please help me?
This is now working! FINALLY FIGURED IT OUT. Had to install Virtual PC 2007 for the VS Emulators. Then configure the Emulator to use the virtual network card.

Categories