I'm new to coding. I'm attempting to access a SQL Server file through WPF / C# and I am having trouble getting in the correct string, I believe. I do not yet fully understand SQL logins, but here is the code I have now, which I believe as close to correct as I can get on my own:
string CS = #"Data Source=(LocalDB)\v11.0; Integrated Security=true; AttachDbFileName=C:\Users\Madison\source\repos\TheRealStudyBot\TheRealStudyBot\TestingData.mdf";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("CREATE TABLE table1 (PK int, Name nvarchar(255), PRIMARY KEY *PK),);", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();
This code is under public MainWindow(), after InitializeComponent(). The file path should be correct. The database is empty. I get this exception:
Win32Exception: Unknown error (0x89c50118)
Ran it once more and I think I may have accidentally altered my debug settings because now it also provides a window stating
The solution does not contain the specified document
(along with plenty of other jargony-code-exception-results-text). I don't see where I'm going wrong. Please help!
If you are on Visual Studio 2019,
Double Click on your LocalDB which opens Server Explorer
Clicking on your database, On the properties tab shows the connection string.
Copy that & Paste on CS!
And the Normal Connection String Format For LocalDB is,
Data Source=Your_DataSource;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False
Related
So, I started to make an app on my main pc. The database works just fine.
But when I move the app on the second Pc,or any other Pc , to continue the work, it chrases, and throws this exception:
System.Data.SqlClient.SqlException: 'An attempt to attach an auto-named database for file C:\Users\Cristi\OneDrive\Documente\Licurici\Licurici\qst.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'
This is the initial connection string :
SqlConnection sqc = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Cristi\OneDrive\Documente\Licurici\Licurici\qst.mdf;Integrated Security=True");
I changed the connection string in:
SqlConnection sqc = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|qst.mdf;Integrated Security=True");
and I also tried this :
SqlConnection sqc = new SqlConnection(Properties.Settings.Default.qstConnectionString);
The last 2 strings work fine, and makes the database portable, but makes INSERT commands not work anymore, at all. This is my sql command:
sqc.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Question(quest, a, b, c, d) VALUES(#q, #a, #b, #c, #d)",sqc);
cmd.Parameters.AddWithValue("#q", richTextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#a", richTextBox2.Text.ToString());
cmd.Parameters.AddWithValue("#b", richTextBox3.Text.ToString());
cmd.Parameters.AddWithValue("#c", richTextBox4.Text.ToString());
cmd.Parameters.AddWithValue("#d", richTextBox5.Text.ToString());
cmd.ExecuteNonQuery();
sqc.Close();
So I am asking you, how do I create a portable(or embedded) database, that will work on any pc, without having to change manually the connection string everytime and also have the possibility to work properly with the sqlcommands like insert ?
I'm working in Visual Studio 2017 with .NET framework.The project is a windows form app.
Any help is appreciated ! :)
I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?
Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later
Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."
While I establish a connection to SQL Server using ADO.NET, it showing errors.
Following is the code:
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=abdul;Integrated Security=true");
SqlCommand cmd = new SqlCommand();
con.Open();
String str="select * from emp where empname='Abdul'";
cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr == null || !dr.HasRows)
{
MessageBox.Show("No Records found");
}
else
{
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
When I am running the project it showing the following error:
Cannot open database "abdul" requested by the login. The login failed.
What have to do?
The login is successful at the the SQL Server level. Then either
the database exists but the login you are using doesn't have access to the database
the database doesn't exist
In SSMS, go to adbul database. Expand the security node and add the relevant users (which map to the login) + security there. If you still can't, have you created the database single user?
It's hard to give more details at the moment.
You need to check that the user you are connecting with is a valid SQL Login, and that the password supplied is correct. You also need to ensure the login has an associated SQL User in the database they are trying to connect to.
SQL Logins are used to access the server itself, and they are mapped to database SQL users.
You said you created the database. How did you do this? Was it from sql management studio? If so, was this in the same Windows session as you are executing the program code above?
I ask because if you could create a database, I believe you should be able to connect to it.
I'd look at the difference between successfully connecting with Sql Management Studio and trying to get past the 3rd line of code in your question. (assuming that's where it fails, maybe even edit the question to take out the lines beyond).
Hello I'm trying to run a simple sql command on a DB from MS VS C# 2010 and I have encountered a error I have never seen before the relevant code is:
SqlConnection comCon = new SqlConnection(#"Data Source=C:\\Users\\George\\Desktop\\programming\\C#workspace\\Projects\\Examen\\Examen\\Companie.mdf;Initial Catalog=Proiect;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Proiect SET Buget = Buget + 500 WHERE (Buget > 0)";
cmd.Connection = comCon;
comCon.Open();
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
comCon.Close();
And the error is Keyword not supported: 'data source'
The main problem is that I'm not used to creating these sqlconnections by hand so please tell me if I'm missing something.
You are using the wrong structure. To attach a database file, you need to use the following structure:
SqlConnection sqlConnection =
"Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;
Database=DatabaseName; Trusted_Connection=Yes";
You need to have the right permissions on both the target file and database server to attach the databse and establish the connection.
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
If it's not an ASP.NET application don't use the DataDirectory syntax and just use the full c:... path.
I'm encountering a problem with my database connection.
I started with a new blank solution, then I added a WCF library project, and last but not least a WCF website (service).
In the website i added a reference to the library where I have the interface (data contract), the class that implements the interface and the dataclasses.
what I'm trying to do is to connect to a database on a server and try to retrieve some data from there.
So the connection string looks like:
<add name="myConnectionString" connectionString="Data Source=MyServer; Initial Catalog=MyDatabase; User Id=me; Password=me123;" providerName="System.Data.SqlClient" />
and this is how I'm trying to connect with the database:
public List<string> GetEngagements(string id)
{
string sql = "SELECT myColumn FROM myTable WHERE Id = '" + id + "'";
string connString = string.Empty;
SqlConnection connDB;
connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
connDB = new SqlConnection(connString);
SqlCommand command = new SqlCommand(sql, connDB);
connDB.Open();
SqlDataReader rdr = command.ExecuteReader();
List<string> numbers = new List<string>();
while (rdr.Read())
{
numbers.Add(rdr[0].ToString());
}
rdr.Close();
return numbers;
}
I'm getting an exception on connDB.Open().
Then exception message says:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
I've been getting this message for 2 days now, I've googled a lot and deleted the C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS directory but it didn't work for me..
Any solution???? help please
The error message:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.
Suggests that you're using user instancing, and therefore your connection string will point to an .mdf file on disk rather than the name of a database.
So I'll assume that you want to connect to a file instance rather than a server instance.
I'll also assume that you're using SqlExpress rather than the full fat version.
In which case your connection string is wrong. It should look more like this:
"Data Source=.\SQLEXPRESS;
AttachDbFilename=fileOnDisk.mdf;
Integrated Security=True;
User Instance=True;"
User instancing means that this server instance and the DB inside will only be visible to the application opening the connection string.
You don't have to use user instancing - you can set User Instance=False or just leave it out. Then once the application has made the connection you can connect other tools to the server instance and connect to the DB yourself.