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.
Related
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)
I am trying to make a simple app that will connect to a database and get some info. I have implented the plugin that allows xamarin app to connect remote mariaDB/MySQL to components. I am using the code below.
public void GetAccountCountFromMySQL()
{
try
{
string sql = " SELECT * FROM Kategorier";
MySqlConnection con = new MySqlConnection("Persist Security Info=False; Server=192.210.241.161; Port=3306; Database=xxxxx; Uid=xxxxx; Pwd=xxxxx;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString("Sko"));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I have tried many types of connection strings, also I buileded a simple C# application that connects to the very same database with no problems.
Actual problem was error from MySql "cannot resolve host name" After discussion the decision was not to use this plugin as it is not secured but create a webservice talking to MySql DB and consume it from Android app.
I am very new in C# and now try to find online resource to connect VS C# to mySQL database at server 'localhost', with userid 'root', and password '****', the databasename is 'dlht'.
1.I copied a line of code from youtube and it works:
this.stockTableAdapter.Fill(this.blhsDataSet.stock);
Can anyone explain to me what exactly this is doing? There is no place to put server, password, userid etc... How can it work?
I tried to use the online tutorials to connect to mySQL database
ZetCode C#Tutorial
string cs = #"server=localhost;userid=root;
password=****;database=dlht";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(cs);
conn.Open();
Console.WriteLine("MySQL version : {0}", conn.ServerVersion);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
I run this code at Form1.cs at VS C#. It is always stuck at :
conn = new MySqlConnection(cs);
Why? Thank you so much!
It seems that the proper way to connect to MySql database is this
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.
I am work on smartApplication, Here when am trying to connect to my SQL Server CE 2005 database, I get the exception
The path is not valid. Check the directory for the database. [ Path = D:\SmartProject\DBFile.sdf ]
My connection string is
Data Source=D:\SmartProject\DBFile.sdf;Password=test123
and the code to connect is like
string connectionString = "Data Source=D:\\SmartProject\\DBFile.sdf;Password=test123";
SqlCeConnection Connection = new SqlCeConnection(connectionString);
SqlCeCommand comm = new SqlCeCommand(SqlSelectCommandText, Connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(comm);
DataSet ds = new DataSet();
try
{
Connection.Open();
da.Fill(ds);
if (ds.Tables.Count > 0)
dataTable = ds.Tables[0];
else
dataTable = new DataTable();
bsuccessfullyExecuted = true;
}
catch (SqlCeException ex)
{
bsuccessfullyExecuted = false;
dataTable = null;
}
finally
{
Connection.Close();
}
when the code try to open the connection it throw this exception provided the file is at the specified location or directory.
It works when I just place the DBFile.sdf file with the .exe in bin and remove the path except the Database file name from connectionstring.
but when I try to access it through Emulator it show this error. provided that its connect through cradle and Windows Mobile Device center.
It show all the page but when I try to access the Db it through exception..
Actually we have to put DBFile.sdf in Mobile Device Folder and now connection string would be
Data Source=\Temp\DBFile.sdf;Password=test123
this Temp is in the Mobile Device folder as our designer session connected to a SQL Mobile database which is on a mobile device connected through ActiveSync.
As a result, the connection string to the database which is automatically generated with the bindingsource is a special connection string that only works from within VS2005 and it begins with DataSource = Mobile Device.....
So for Emulator we have to put sdf file in Mobile Devide and as above