I'm trying to set up a local database (Service-based Database) in my C# app. When I intially adds the database to the project, I can see it and edit tables in both VS and SSMS, but when I try to connect to it programmatically, I get this error:
"Cannot open database \"[DataDirectory]DATABASE.MDF\" requested by the login. The login failed.\r\nLogin failed for user 'DESKTOP-MM6AR72\\majbom'."
And after that, the database is gone from both VS and SSMS.
I'm connecting this way:
using(SqlConnection conn = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=[DataDirectory]DATABASE.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
{
using(SqlCommand cmd = new SqlCommand(SQL, conn))
{
cmd.Connection.Open();
}
}
I have never tried to use databases this way, so maybe I'm doing something wrong. What I'm trying to accomplish, is a way of storing a lot af data temporarily in my app and make it searchable and editable.
EDIT:
I've followed this guide: https://learn.microsoft.com/en-us/visualstudio/data-tools/create-a-sql-database-by-using-a-designer
Thanks in advance
Related
I am attempting to connect to a local SQL Server database in C#.
I am currently using the following connection string:
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\majorWork\majorWork\gameStats.mdf;Integrated Security=True";
However, I do not want to use a hardcoded file path, as I wish to be able to use the application across multiple computers, where the file path will be different. How should I go about doing this?
Best way is set this connection in Web.Config file.
<Database>
<ConnectionString name="connection">Server=servername; Initial Catalog=dbname; Persist Security Info=False; User ID=username; Password=password; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30;;</ConnectionString>
</Database>
Then add Add System.Configuration as a reference.
in C# you can call this
string constring = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
After that you can create new connection instance by passing this to
SqlConnection con = new SqlConnection(constring)
If u install SQL server express using the default instance, then you can connect using . as your server name anyone can use it with default instance as well.
1.then in visual studio, click on solution explorer
2. Connect database, follow the instruction for SQL server
3. When it gets to server name use . to connect and choose your database name which you have created already in ms SQl, then test your connection
4. After it successful, u can now click on the database name showing under solution explorer,
5.after u click the database name, at the button right corner, there will be a connection string, copy it and use
This will be declared publicly or globally
Sqlconnection con = new sqlconnection("paste the connection string");
And to use
Sqlcommand cmd = new sqlcommand("insert into......",con);
Con.open ();
Cmd.executenonquery();
Con.close();
I'm trying to connect ms access database using c#. While doing that I'm stuck at one place.
Whenever i try to open the connection using
OleDbConnection conn = new OleDbConnection("connection string valid");
conn.Open();
I get error that whichever is the provider, it is not registered onto the local machine !
I have downloaded the msaccessEngine also from well known link http://www.microsoft.com/en-us/download/details.aspx?id=13255.
I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.
I'm trying to search the Indexing Service of a remote Windows 2003 server from ASP.NET. There's sample code for this on the MS site, but only for local searches. Here's what I've got so far; the remote server in this example is called "indexserver", isn't on a domain, and has a index called "system":
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=MSIDXS;User ID=administrator;Password=Password";
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText= "SELECT * FROM indexserver.system..FILEINFO";
conn.Open();
cmd.ExecuteReader();
Running this gives me the error "Multiple-step OLE DB operation generated errors. Check the OLE DB status if available. No work was done".
Does anyone know how to get this working? All I need to do is query the Index for a filename and get the path of that file back.
Never mind, I discovered that Windows Indexing Service is somewhat depreciated,and Windows Search seems to be the way to go...
We are trying to build a Help Desk ticketing system just for intranet. Deciding upon the ASP .NET (C#) with Visual Studio 2008 Express (think we have a full version floating around if we need it). Nothing fancy, couple of pages grabbing NTLM information, system information and storing it along with their problem in a database. Goal is to make it simple, but instead of using our SQL Server 2000 back end, the admin wants me to use MS Access. I have the GridView and connections running smooth. Can pull select queries until my heart is content. However, tying in a couple variables with a text box on a submit button into say an INSERT statement.. well I don't even know where to begin with MS Access. Every internet example is in VB .NET plus seems to be hand coding what Visual Studio has already done for me in a few clicks.
Is MS Access going to be too hard for all we want to do? If not, where do we begin to simply submit this data into the tables?
Edit: After a bunch of playing around we have the OleDB working. It's not pretty, yes SQL Server would be awesome but, sometimes you just have to play ball.
Edit: Anyone looking for an actual coded answer, here you are. There has got to be others out there in the same boat.
string userIP = Request.UserHostAddress.ToString();
string userDNS = Request.UserHostName.ToString();
string duser = Request.ServerVariables["LOGON_USER"]; //NTLM Domain\Username
string computer = System.Environment.MachineName.ToString(); //Computer Name
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\helpdesk.MDB;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO ticketing ([user], [comp], [issue]) VALUES (#duser, #computer, #col3)";
cmd.Parameters.Add("#duser", OleDbType.VarChar).Value = duser;
cmd.Parameters.Add("#computer", OleDbType.VarChar).Value = computer;
cmd.Parameters.Add("#col3", OleDbType.LongVarChar).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
conn.Close();
The admin is nuts. Access is an in-process database, and as such is not well suited for web sites where users will be creating or updating records.
But as far as creating INSERT queries go, Access is no harder than anything else. If you can't create INSERT queries for Access you'll probably have trouble with SQL Server as well.
I also suggest using SQL Server, but considering your problem:
What is your problem writing an INSERT query for Access ?
You should make use of the classes that you'll find in the System.Data.OleDb namespace:
OleDbConnection
OleDbCommand
Quick'n dirty code (not compiled whatsoever):
OleDbConnection conn = new OleDbConnection (connectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText= "INSERT INTO myTable (col1, col2) VALUES (#p_col1, #p_col2)";
command.Parameters.Add ("#p_col1", OleDbType.String).Value = textBox1.Text;
...
command.ExecuteNonQUery();
There are some caveats with the OleDb classes however (like adding the Parameters to the collection in the order that they occur in your SQL statement, for instance).
Don't bother with Access. Use SQL Server Express. There's also an admin tool for it that looks like the full blown SQL Server management tool.
Access has its place, and can usually do more than what most people give it credit for, but yes you want to use SQL Server in ones of its many forms (eg. SQL Server Express) or another proper "server" database for a web app like this.