I developed an application. It loads sql database on my pc with this connection string:
Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True");
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("SELECT * FROM Lessons", con);
da.Fill(ds);
grdPersonnel1.DataContext = ds.Tables[0];
con.Open();
}
but, my Database data doesn't load in another pc!
Do you have SQL server instance Running on that Computer?
Try to Run your Application/Solution on the other P.C on Debug Mode you will see what exactly is the error...make sure you have try and catch in each of your methods/ events.
check this SO post :
Is it possible to run a mdf database without SQL Server program? (c#)
Connecting to sql server database mdf file without installing sql server on client machine?
Regards
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'm trying to pass data from DataGridView to a Database SqlClient I opened especially for this. When the program runs, it tells me this error:
An attempt to attach an auto-named database for file failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I made a form with 2 buttons, one for adding data to the DataGridView (works fine) and another one to pass the data to a database table.
the not working button's code is this:
private void button3_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=.;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sql = "SELECT * FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
con.Open();
dataadapter.Fill(ds, "Authors_table");
con.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
What can I do to fix it?
I tried choosing a data source to the DataGridView but it still didn't work out.
Thanks in advance!
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.
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.
I want to create a program for my school, handling marks and certificates.
To save the data I have to use a "local" network shared database-file, because we are using Citrix and there is no possibility to setup an seperate SQL-Server.
I tried it with localdb v11 with the following code:
string connectionString = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=D:\_prog\TestNoten\TestNoten\bin\Debug\Database1.mdf; Integrated Security=True;Connect Timeout=3;";
SqlConnection connection = new SqlConnection(connectionString);
string sql = "INSERT INTO test(name) VALUES('lal')";
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
DataTable table = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("Select * from test", connection);
connection.Open();
adp.Fill(table);
MessageBox.Show(table.Rows[0][1].ToString());
The MessageBox says "lal", but when I restart the program with "lala" instead of "lal", it will show "lala" and not the expected "lal".
So when closing the program, the database won't be saved correctly. I also opened the file over VSs Data Connections, and the testing table is empty.
Is there something I missed?