Reputation: 448
I get an exception error for my code. Please help me - what is the problem? (I'm new to this :/)
My database is local database.
SqlConnection myconnection;
private void insertBtn_Click(object sender, EventArgs e)
{
myconnection = new SqlConnection();
myconnection.ConnectionString = "Data Source=C:\\Users\\Saeed\\Documents\\Visual Studio 2012\\Projects\\dictionary1\\dictionary1\\Database1.sdf";
myconnection.Open();
//string query = "INSERT INTO dictionary (id,enWord,faWord) VALUES (4,'pen','خودكار')";
//SqlCommand cmd = new SqlCommand(query, myconnection);
//cmd.ExecuteNonQuery();
}
Here is the exception error:
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)
Upvotes: 0
Views: 1304
Reputation: 76607
Since you are accessing a SQL Server Compact Database .sdf
file, you will want to use the SqlCeConnection
and SqlCeCommand
classes as opposed to the SqlConnection
and SqlCommand
classes, which you would use for traditional SQL Server connections.
Additionally, you can try using the Persist Security Info=False;
setting within your connection string using an example similar to the ones mentioned on ConnectionStrings.com using
private void insertBtn_Click(object sender, EventArgs e)
{
// Open your connection
using(var myConnection = new SqlCeConnection(@"Data Source=C:\Users\Saeed\Documents\Visual Studio 2012\Projects\dictionary1\dictionary1\Database1.sdf;Persist Security Info=False;"))
{
// Build your query
var query = "INSERT INTO dictionary (id,enWord,faWord) VALUES (4,'pen','خودكار')"
// Build a command to execute
using(var myCommand = new SqlCeCommand(query,myConnection))
{
// Open your connection
myConnection.Open();
// Execute your query
myCommand.ExecuteNonQuery();
}
}
}
Upvotes: 2
Reputation: 364
Your connection string is incorrect. It needs to look something like this:
"Persist Security Info=False;Integrated Security=true;Initial Catalog=YOUR_DATABASE_NAME;server=(local)"
See here for more information on connection strings: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx
Upvotes: -1