I'm having immense trouble getting a connection to a .sdf (sql compact edition) database. I can connect initially to extract rows in order to verify a username/password, but when I try to add items to the database, either by a SqlCeConnection/SqlCeCommand command or by trying to add items SqlClient/SqlCommand connection, I have no luck. I get:
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)
when using:
private void button1_Click_1(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
or when I try:
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Data Source=C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
Nothing happens, it seems to work until I check the .sdf file and see nothing has been added. I do not have SQL Server CE installed, though I do have 2008 R2 installed (I'm working on someone else's project).
Right now I'm not worried about the security holes, I'm just trying to successfully add a record. Any help would be much appreciated, as I've spent about three or four hours working on something I figure would take about 20 minutes.
Probably you have found the solution by now, but if you use a sdf file, the assembly you should add a reference to System.Data.SqlServerCe and then something like:
SqlCeConnection sqlConnection1= new SqlCeConnection();
sqlConnection1.ConnectionString = "Data Source = C:\\Users\\Tim\\Documents\\Visual Studio 2010\\Projects\\Dispatch POS\\Dispatch POS\\GhsDB.sdf";
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT [Employee Table] (SSN, FirstName) VALUES ('555-23-4322', 'Tim')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
you most to use sqlceconnection and sqlcecommand classes. like this :
SqlCeConnection conn = new SqlCeConnection(connectionString);
SqlCeCommand cmd = conn.CreateCommand();
conn.Open();
Related
I'm trying to insert some data into my DB (Microsoft SQL Server)
My connection does not open and I get this message:
Cannot open database \"[Sales and Inventory System]\" requested by the login. The login failed.\r\nLogin failed for user 'Mostafa-PC\Mostafa'.
here is my code:
public void InsertProduct(List<string> _myName,
List<int> _myAmount,
List<int> _myPrice, string _date)
{
string connectionString = #"Data Source=MOSTAFA-PC;Initial Catalog=[Sales and Inventory System];Integrated Security=True";
string query = #"INSERT INTO dbo.product(Name, Amount, Price, [date])
VALUES(#Name, #Amount, #Price, #Date);";
using (SqlConnection Con = new SqlConnection(connectionString))
using (SqlCommand Cmd = new SqlCommand(query, Con))
{
Cmd.Parameters.Add("#Name", SqlDbType.NVarChar);
Cmd.Parameters.Add("#Amount", SqlDbType.Int);
Cmd.Parameters.Add("#Price", SqlDbType.Int);
Cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = Convert.ToDateTime(_date);
Cmd.Connection = Con;
Con.Open();
int recordsToAdd = _myName.Count();
for(int x = 0; x < recordsToAdd; x++)
{
Cmd.Parameters["#Name"].Value = _myName[x];
Cmd.Parameters["#Amount"].Value = _myAmount[x];
Cmd.Parameters["#Price"].Value = _myPrice[x];
Cmd.ExecuteNonQuery();
}
}
I've done everything and I've searched everywhere. I cannot figure out why.
It seems like you need to check below things to solve your error.
1. Check permission. User must have access to this Database. Most Important One
2. Also, It would be better to access App.config key to code side. So declare connection string in app.config and try to set like below.
string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["keyname"]
3. You also need to try connecting the instance in SSMS and It should not be failed.
This Link can be helpful to you for more information.
The error is definitely permission related.
Check permission of the account on the instance and DB.
And make sure the DB really exists on the server. Sometimes, it complains about permission but DB doesn't even exist.
I am using VS 2012 Express for web, I have created a website project and I am trying to connect integrated SQL Server with on the .aspx page of the website but I am getting an 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)
I have gone through various websites and tried to connect via web.config as well as c# but its does not seem to be possible.
What I have tried so far
web.config file:
<connectionStrings>
<add name="CnStr"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
C# code:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CnStr"].ConnectionString;
SqlConnection conn = new SqlConnection("connectionString");
SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
conn.Close();
The other way I have tried is:
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;Database=Visual Studio 2012\\App_Data\\Database.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
conn.Close();
I have made database using following steps
right click on project
selecting SQL Server database to App_Data folder with name Database.mdf
Also If I try using add connections from data connections in database explorer, it's not accessing the database.mdf file and load only the templates e.g master, temp etc and not the folder in my App_Data folder and giving same error.
I have gone through many questions in stack overflow and tried using them as well
This is not code error, but a SQL configuration error. Follow steps in this excellent article for troubleshooting.
http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/
try this code instead!!!
string str = "Data Source=(LocalDB)\\v11.0;Database=Visual Studio 2012\\App_Data\\Database.mdf;Integrated Security=True";
using(SqlConnection conn = new SqlConnection(str));
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
{
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
conn.Close();
}
I run the code below
var connectionString="Data Source=MyFooServer.myDomaion.com;Initial Catalog=FooDb;Integrated Security=True; MultipleActiveResultSets=true";
using (var con = new SqlConnection(connectionString))
{
var q = "SELECT COUNT(*) FROM Pizza";
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = q;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
reader = cmd.ExecuteReader();
con.Close();
}
from 2 different places:
1) LinqPad
2) A Console application in Visual Studio 2010
LinqPad works fine. No exceptions.
But the same code throws an SQL exception: "The target principal name is incorrect. Cannot generate SSPI context."
QUESTION: Why I can connect to my database without any problem from LinqPad but not from the console application even tough I run the same code?
Rebooting my machine helped... No idea what was the root cause of this behavior tough.
Try to use SQL username and password instead of Windows Inegrated Security.
var connctionString="Data Source=MyFooServer.myDomain.com;Initial Catalog=FooDb;Uid=Username; pwd=password"
I'm quite used to using c# with SQL server. I have no idea why a simple statement would fail to insert data. My code is as follows:
query = "INSERT INTO MCDPhoneNumber ([MCDID],[PhoneNumber])" +
"VALUES("+maxid+", '"+tel+"')";
SqlConnection conn = new SqlConnection("Data Source=source; ...");
SqlCommand newCommand = new SqlCommand(query, conn);
int success= myCommand.ExecuteNonQuery();
if (success!= 1)
{
MessageBox.Show("It didn't insert anything:" + query);
}
First of all let me tell that I know that I should use parameters for data and I initially did, but when it failed I tried a simple query and it still fails. For addition I can tell that I have a similar insert just before that one in another table and it works. What's funnier is that when I copy paste query to SQL Server Management Studio it works. It also doesn't report any error in process.
====================== Edit ===============================
If you wish to use old command object (i.e. myCommand) then use following code instead of creating a new command(newCommand)
myCommand.CommandText = query;
myCommand.CommandType = System.Data.CommandType.Text;
And then execute it
you are binding query with newCommand and executing myCommand.
====================== Edit ===============================
SqlCommand newCommand = new SqlCommand(query, conn);
here you have defined newCommand for SQLCOMMAND object
int success= myCommand.ExecuteNonQuery();
and you are accessing it as myCommand
And moreover i think you are not opening connection
First of all, you define your command as newCommand but you executing your myCommand.
You should always use parameterized queries for your sql queries. This kind of string concatenations are open for SQL Injection attacks.
query = "INSERT INTO MCDPhoneNumber (MCDID, PhoneNumber) VALUES(#maxid, #tel)";
using(SqlConnection conn = new SqlConnection("Data Source=source; Initial Catalog=base; Integrated Security = true"))
{
SqlCommand newCommand = new SqlCommand(query, conn);
conn.Open();
newCommand.Parameters.AddWithValue("#maxid", maxid);
newCommand.Parameters.AddWithValue("#tel", tel);
int success= newCommand.ExecuteNonQuery();
if (success != 1)
{
MessageBox.Show("It didn't insert shit:" + query);
}
}
And please be more polite about your error messages :)
I am trying to access an Access 2003 database remotely from my ASP.NET application. My code is:
DataSet dsImportedData = new DataSet();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=MS Remote;Remote Provider=Microsoft.Jet.OLEDB.4.0;Remote Server=http://myIp;Data source=C:\myDatabase.mdb;";
try
{
System.Data.OleDb.OleDbCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command);
adapter.Fill(dsImportedData);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
However, I am always getting an exception stating: {"[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."}
My command is basic, I have no idea what could be wrong with it. Did anyone confront with the same issue? Thanks!
Try this ....
String command = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command, conn);
adapter.Fill(dsImportedData);
Apparently the error can be caused by the specified table not existing. Just a thought...
Another thought would be to remove the remoting complexity and try to get to the most simple working code, possibly with a new access database just to start to narrow down what is causing the problem.
If you set the command type to Stores procedure it works for me.
command.CommandType = System.Data.CommandType.StoredProcedure;