I'm trying to retrieve records to my data gridview dgvEmployees from my table tblEmployees. I'm not sure what's wrong though, maybe because of the syntax? But the code has worked before using MS Visual C# 2010 Express (WinForms only). I'm currently creating a webpage with winforms using MS Visual Studio (ASP.NET - C#). Here's my code:
SqlConnection sConn;
SqlDataAdapter daEmp;
DataSet dsEmp;
const string sStr = "Server = MYSERVER\\SQLEXPRESS; Database = EMPLOYEES; Integrated Security = SSPI";
protected void Page_Load(object sender, EventArgs e)
{
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("Select * from tblEmployees", sConn);
dsEmp = new DataSet();
daEmp.Fill(dsEmp, "tblEmployees");
dsEmp.Tables["tblEmployees"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployees"].Columns["EmployeeID"] };
dgvEmployees.DataSource = dsEmp.Tables["tblEmployees"];
}
Here's the error message on this line (daEmp.Fill(dsEmp, "tblEmployees");
Invalid object name 'tblEmployees'
Please help. Thanks!
The error is referring to the SQL query not the DataSet. In other words the issue is not with the C#. You need to check your connection string and make sure the table exists in the DB.
daEmp = new SqlDataAdapter("Select * from tblEmployees", sConn);
This query is bad: Select * from tblEmployees
You can verify this by changing the query to: Select * from IDONTEXIST
You will see a similar error:
invalid object name IDONTEXIST
You are now running the application on the website so the user that will connect to SQL server is the one that is running your application pool in IIS when you use Integrated Security = SSPI in your connection string.
You need to either:
Give access to the database for the application pool user (not a good idea for the default one).
Change the user for the connection pool to a user who has access to the database.
Specify a user who has access in the connection string.
You should first verify your connection string:
Ensure it is connecting to the SQL Server instance you think it is.
Ensure that it is establishing the database context for the connection in the database you think that it is.
Ensure that it is connecting with the credentials you think that it is.
Ensure that those credentials map to the SQL Server user you think that it should
That that SQL Server user has the default schema you think it does and that it has appropriate rights granted in the database.
Almost certainly, your problem derives from one or more of the issues listed above.
If your database context for the connection is in a different database than you think, you probably won't find the objects you're looking for.
If your object references are not schema-qualified, you may have a problem resolving object references. Object references in your SQL queries should always, at the very least, be schema-qualified. Instead of saying
select * from tblEmployees
you should be saying
select * from dbo.tblEmployees
where dbo is the schema that owns the object. Any object references that are not schema-qualified are looked up at run time in the following order
First, the current user's default schema is probed for an object of the desired name.
If that fails, the dbo schema ('data base owner') is probed for an object of the desired name.
For stored procedures, the lookup is more complex:
Probe the current user's default schema in the current database.
Probe the 'dbo' schema in the current database.
If the stored procedure name begins with 'sp_',
Probe the current user's default schema in the 'master' database.
Probe the 'dbo' schema in the 'master' database.
If the object in question belongs to another schema, it will not be found unless qualified by the owner schema.
Due to the multiple lookup issue, lack of schema-qualification can prevent execution plan caching, meaning that the query plan has to be recompiled on every execution of a query. Needless to say, this has...sub-optimal effects on performance.
Further, you may get...interesting...results if your database user is 'dev' and the dev in question, 6 months back, created a table or other object named 'dev.foo' during development. Now you're live in production and connecting as user 'dev'. Executing select * from foo will bind to dev.foo in preference to the actual production table that the DBA created, 'dbo.foo'. Your users will be wondering why their data is missing or you'll be ripping your hair out wondering why the app is whining about missing columns when they appear to be all there when you look at it via the SQL Management Studio.
Related
Microsoft documentation indicates that an app using the code-first approach can simply specify the model, and the database will be created if it does not already exist.
But I want my app to store it's data in a database on the end-user's hard-disk. So I can refer to localdb (for SQL Server) in my connection string, but I still don't know what folder on the user's machine will have the database files.
How can a user back up her data files, if she doesn't know where they are?
Is there some way to ask the DbContext object where it's files are stored?
I know I can specify the path of the database when it is created via SQL, but I've been told that it is not good form to mix EF-style database interaction with non-EF database interaction (from ADO.NET).
From the Microsoft documentaion page:
User database files are stored where the user designates, typically
somewhere in the C:\Users\UserName\Documents\ folder.
So the person or setup program installing the SQL Express localdb knows where the database is.
EDIT:
To set the connection string at runtime, you can pass a connection string, instead of a connectionstring name, to your db context. You can create your connection string on your own or use a EntityConnectionStringBuilder.
// Manually build the connection string
var connectionString = "Server=(LocalDB)\MSSQLLocalDB; Integrated Security=true;AttachDbFileName=" + pathToDatabase;
var dbContext = new YourDBContext(connectionString);
I have an ASP.Net Web Forms app that is inserts new records (requests) into a SQL Server table using a SqlCommand and using the ExecuteNonQuery method. The table has a single primary key (int id) that is set for Identity Specification = Yes, Identity Increment 1, Identity Seed 1. The app has been working for years. About a month ago, the database was moved from a physical server to virtual server without any apparent issues. The database is running on SQL Server 10.50.1617.0.
Very recently, a user reported creating about 90 requests but not being able to find them. When I examined the request table, I could only find one request created for her in the last few days. The highest id on the request table was 5404. As an experiment, I had her create a new request. I was expecting it to create a new id of 5405, but it actually created an id of 2975. I had her create another request and it over-wrote the first request with another on id 2975. I created a test request and it created one at id 5405. What could possibly cause this?
Here is the c# for the insert:
string sql = "insert into requests (end_user_email) values (#email)";
SqlConnection cn = new SqlConnection(_cnString);
SqlCommand cmdIns = new SqlCommand(sql, cn);
cmdIns.Parameters.Add("#email", SqlDbType.NVarChar);
cmdIns.Parameters["#email"].Value = email;
cmdIns.Connection.Open();
cmdIns.ExecuteNonQuery();
Your table name is not schema-qualified (e.g., dbo.requests). I suspect you've got two different tables in your database with identical names. One is owned by the dbo schema; the other by your default schema.
SQL Server name resolution works as follows for unqualified references:
Probe the namespace for an oject of the specified name under the default schema as defined by the current connections credentials. If one is found, that object resolves the reference. Otherwise...
Probe the namespace for an object of the specified name under the dbo schema. If one is found, that object resolves the reference. Otherwise...
If the object is a stored procedure whose name begins with sp_, further probes of the namespace are performed against the master database as in steps #1 and #2 above.
Finally, if the reference was not resolved, name resolution fails.
Your user is connecting using credentials with one default schema and resolving to a table named requests that is either owned by that schema or dbo.
You, on the other hand, are using credentials with another default schema and finding a different table with the same name, either owned by your default schema or dbo.
One should always schema-qualify object references, for two-reasons:
Performance. Two probes of the namespaces to find the dbo-owned object that you probably want costs you in terms of performance.
Further, execution plans involving unqualified references may not get cached, leading to additional recompiles.
Lastly, you or somebody else will, at some point, shoot yourself in the foot. Often, it will be by one party executing one version of a stored procedure and another party a different version. Hilarity ensues -- "It works on my machine!". Even better is when different people are hitting different versions of the same table, receiving seemingly random errors regarding missing columns.
HOWEVER...
It's not unheard of :-) for identity columns to have the value of the identity property get out of sync with data for various reason.
So, if you've ruled out two different flavors of the same table, you'll want to have your DBA run DBCC CHECKIDENT against the table to get the table's identity counter back in sync with the high-water mark in the table.
DBCC CHECKIDENT( {table-name} , noreseed )
reports on the current values of both the identity counter for the table and the current high-water mark in the table.
DBCC CHECKIDENT( {table-name} , reseed )
reseeds the identity counter to match the high-water mark in the table.
It's also possible the client moved from a single server to a sand box or cloud & failed to change the web.config of the application..
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
in this case it may also benefit to move to an nvarchar(128) or GUID & use newID() to assign unique ID's to additional records.
I am trying to create a database, but once created, I cannot connect to it.
The server is Microsoft SQL Server 2008 and using .Net 4.5. We're creating the database with SMO, but we're usually using Dapper to connect and query the database.
This is the code I have so far, which works :
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(connectionString);
Microsoft.SqlServer.Management.Smo.Server srv = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(con));
var database = new Microsoft.SqlServer.Management.Smo.Database(srv, dbName);
database.Create(false);
database.Roles["db_datareader"].AddMember(???);
database.Roles["db_datawriter"].AddMember(???);
database.Roles["db_backupoperator"].AddMember(???);
srv.Refresh();
Noce the ??? ? I have tried
System.Environment.UserDomainName + "\\" + System.Environment.UserName
and
System.Environment.UserName
but it fails (update) with the error Add member failed for DatabaseRole 'db_datareader'. with both values.
The problem is that when I create the database, I cannot coonect to it for some reason (using Dapper), from the same program. (update) I get the error message : Cannot open database \"<database_name>\" requested by the login. The login failed.\r\nLogin failed for user '<domain>\\<username>' (where <database_name> is the database name, <domain> my logon domain, and <username> my Windows logon).
Am I missing something? Am I doing th right thing? I've tried searching the web, but it seems no one creates database this way. The methods are there, it should work, no?
** Update **
If I comment the database.Roles["..."].AddMember(...) lines, and I add a break point at srv.Refresh(), resuming the program from there solves everything.
Why a break point solves everything? I can't just break the program in production... nor break the program when creating the database everytime.
It sounds like the Dapper connection issue is a problem with SQL Server doing some of the SMO operations asynchronously. In all likelihood, the new Database is not ready for other users/connections immediately, but requires some small time for SQL Server to prepare it. In "human-time" (in SSMS, or a Breakpoint) this isn't noticeable, but "program-time" it too fast, so you probably need to give it a pause.
This may also be the problem with the Role's AddMember, but there a a number of things that could be wrong here, and we do not have enough information to tell. (specifically, does AddMember work later on? and are the strings being passed correct or not?)
This is happening because you've created the user, but no login for that user. Though I don't know the exact syntax, you're going to have to create a Login. You'll want to set its LoginType to LoginType.WindowsUser. Further, you'll likely need to set the WindowsLoginAccessType to WindowsLoginAccessType.Grant and you'll need to set the Credential by building one, probably a NetworkCredential with the user name you want.
To put a visual on this, the Login is under the Security node for the Server in Management Studio whereas the User is under the Security node for the Database. Both need to exist for access to the SQL Server.
I am a beginner in working with databases. I am trying to access Oracle10g database from a c# application. But when I do so i get this error:
ORA-12154: TNS:could not resolve the connect identifier specified"
I'm using the following code:
string oradb = "Data Source=ORCL;User Id=system;Password=goodbye;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
Is there an error in the connection string oradb?
Start the Visual Studio, open View menu + Server Explorer.
Right mouse click on Data Connection + Add Connection + Select Oracle Database
server Name : localhost or name of your machine, set username & password and click on Test Connection to verify the above parameters. Press OK if test is succeeds.
From properties windows you can obtain connection String and it should be look a like:
Data Source=localhost;Persist Security Info=True;User ID=scott;Password=***********;Unicode=True
Oracle is just stating that it can't find the database.
If you're running a local Express Edition database, you should be able to just use XE as an instance name, and everything should already be set up, otherwise you can most easily add it to tnsnames.ora.
To find the correct tnsnames.ora to change, you can try (from the command prompt)
tnsping ORCL
That will tell you which files Oracle is using to try to find the database. If tnsping is an unknown command, you may have to search for it and go to the correct place before running it.
One you found the correct tnsnames.ora, you need to add the instance ORCL to it. There should be an existing file with examples, the syntax of that file is too complex to answer here, if you need help, Oracle has quite extensive documentation.
This is a very common oracle error. Simply put, it means that you have named the database you wish to be connected to and Oracle doesn’t know who the heck you’re talking about. I suggest 6 Steps to fix ORA-12154:
Check instance name has been entered correctly in tnsnames.ora.
There should be no control characters at the end of the instance or database name.
All paranthesis around the TNS entry should be properly terminated
Domain name entry in sqlnet.ora should not be conflicting with full database name.
If problem still persists, try to re-create TNS entry in tnsnames.ora.
At last you may add new entries using the SQL*Net Easy configuration utility.
More informations on oracle site or here : http://turfybot.free.fr/oracle/11g/errors/ORA-12154.html
I'm making an app that will be installed and run on multiple computers, my target is to make an empty local database file that is installed with the app and when user uses the app his database to be filled with the data from the app .
can you provide me with the following examples :
what do I need to do so my app can connect to its local database
how to execute a query with variables from the app for example how would you add to the database the following thing
String abc = "ABC";
String BBB = "Something longer than abc";
and etc
Edit ::
I am using a "local database" created from " add > new item > Local database" so how would i connect to that ? Sorry for the dumb question .. i have never used databases in .net
Depending on the needs you could also consider Sql CE. I'm sure that if you specified the database you're thinking of using, or your requirements if you're usure you would get proper and real examples of connection strings etc.
Edit: Here's code for SqlCe / Sql Compact
public void ConnectListAndSaveSQLCompactExample()
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);
DataSet data = new DataSet();
adapter.Fill(data);
// Add a row to the test_table (assume that table consists of a text column)
data.Tables[0].Rows.Add(new object[] { "New row added by code" });
// Save data back to the databasefile
adapter.Update(data);
// Close
connection.Close();
}
Remember to add a reference to System.Data.SqlServerCe
I'm not seeing anybody suggesting SQL Compact; it's similar to SQLite in that it doesn't require installation and tailors to the low-end database. It grew out of SQL Mobile and as such has a small footprint and limited feature-set, but if you're familiar with Microsoft's SQL offerings it should have some familiarity.
SQL Express is another option, but be aware that it requires a standalone installation and is a bit beefier than you might need for an applciation's local cache. That said it's also quite a bit more powerful than SQL Compact or SQLite.
Seems like you're:
-Making a C# app that will be installed and run on multiple
computers
-That needs a local database (I'm assuming an RDBMS)
-You need to generate a blank database at installation
-You then need to be able to connect to the database and populate it when
the app runs.
In general, it seems that you need to read up on using a small database engine for applications. I'd start by checking out SQLite, especially if you need multi-OS capability (eg., your C# program will run on Microsoft's .NET Framework and Novell's Mono). There are C# wrappers for accessing the SQLite database.
I believe this question is about the "Local Database" item template in Visual Studio:
What are you considering as a database? From what little you've provided in your question, I'd suggest SQLite.
You can get sample code from their site Sqlite.NET
Not sure I fully understand what you're asking but Sqlite is a good option for lightweight, locally deployed database persistence. Have a look here:
http://www.sqlite.org/
and here for an ADO.NET provider..
http://sqlite.phxsoftware.com/
For 1)
The easiest way to provide this functionality is through SQL Server Express User Instances. SQL Server Express is free, so your user does not have to pay additional license for SQL Server, and the User Instance is file-based, which suits your requirement.
For 2)
This is a big topic. You may want to go through some of the tutorials from Microsoft to get the feeling of how to connect to DB, etc.