Open a connection to a local DB asp.net MVC - c#

I'm trying to open a connection to a DB and then insert a record into a table. At the moment it's just a simple localDB, I have looked at opening the connection with the sqlclient namespace methods.
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;
AttachDbFilename=C:\\FILE\\PATH\\EXAMPLE\\TechMVCDB.mdf;Integrated Security=True;
Connect Timeout=30");
I'm not certain that my connection string is even correct, I got it directly from the connection string box when you click on your database in the server explorer panel. I added a breakpoint in the code after the connection was opened and a select all statement was executed :
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\FILE\\PATH\\EXAMPLE\\TechMVCDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "SELECT * FROM Table ORDER BY Id";
SqlDataReader rdr = com.ExecuteReader();
I then get this error "System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.'" Table was just simply the name of the table was it also treating it as a keyword?
After this I changed the tablename to TechTester and ran it again, it ran with no errors and seemed to get the correct field amount of 4 id,sequence,direction,time it didn't seem to get the inserted test data.
I've also looked at using the Entity framework and implemented the very beginnings of it so I have my entity model class setup but nothing more. Is this the direction I should actually go with? How would I access the entity database?
My question is How do I best open a connection to a local db in asp.net-MVC using C#?

Table is one of the SQL Server reserved keywords.

Related

Exception when attempting to connect to SQL Server CE from C#

I'm an newbie who is trying to get learn some web programming. I'm making my site in VS 2012 using C#. I've got a database connected in the App_Data folder, using SQL Server CE 4.0. I'm attempting to connect to it as follows:
SqlCeCommand cmd1 = new SqlCeCommand("SELECT Admin FROM SystemUsers WHERE Email=" + user.Email);
SqlCeDataReader admin = null;
SqlCeConnection conn = new SqlCeConnection();
conn.ConnectionString = "Data Source=MyData.sdf;Persist Security Info=False;";
conn.Open();
admin = cmd1.ExecuteReader();
When I execute this, I get the following error:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code
Any thoughts as to what I'm doing wrong? I've been trying to figure this out for hours.
You said that your database is in the APP_Data directory, but your connection string assumes that is in the root directory of your site.
Try with
conn.ConnectionString = #"Data Source|DataDirectory|\MyData.sdf;Persist Security Info=False;";
The |DataDirectory| is a placeholder string that the NET Framework changes to a predefined location where you data files are supposed to stay
And this is how I would change your code
using(SqlCeConnection conn = new SqlCeConnection(#"Data Source|DataDirectory|\MyData.sdf;Persist Security Info=False;"))
using(SqlCeCommand cmd1 = new SqlCeCommand("SELECT Admin FROM SystemUsers WHERE Email=#mail", conn))
{
conn.Open();
cmd1.Parameters.AddWithValue("#mail", user.Email);
SqlCeDataReader admin = cmd1.ExecuteReader();
while(admin.Read())
{
.....
}
}
As you can see, I have made this changes:
Added a using statement around the creation of the connection and of
the command. This will ensure proper closing and disposing of the two
objects.
Added a parameterized query to avoid problems in parsing text strings
and Sql Injections

Connecting to local SQL Server database using C#

Suppose I have created a SQL Server database called Database1.mdf in the App_Data folder in Visual Studio with a table called Names.
How could I establish a connection to read the table values using C#?
So far I've tried something like this:
SqlConnection conn = new SqlConnection("Server=localhost;Database=Database1;");
conn.Open();
// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Names";
But I get an error:
database not found/error connecting to database
In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there
If you use SQL authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication, use this:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you're using SQL Server express, change
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/
SqlConnection c = new SqlConnection(#"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
You try with this string connection
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
I like to use the handy process outlined here to build connection strings using a .udl file. This allows you to test them from within the udl file to ensure that you can connect before you run any code.
Hope that helps.
Visual Studio 2019 (and probably a few previous versions).
View -> SQL Server Object Explorer
Top of the tree is 'SQL Server'
Under 'SQL Server', are couple of '(localdb)....'
Expand the (localdb)... -> Databases until you find your db.
Database Name (eg. Database1) -> Right-click -> Properties, and scroll the many properties (eg. "ANSI
NULL Default"). Find the "Connection string" property, copy the value
into your code, and you're running.

the requested operation requires sql clr context

I am getting an error while connecting to the sql from my cs file. I am trying to create CLR functions in c# without using any IDE which is the requirement. I need to access the database to get some value. Following is the code to connect to my database in c#.
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn);
SqlContext.Pipe.ExecuteAndSend(cmd);
return (int)cmd.ExecuteScalar();
}
but I am getting the following error:
"The requested operation requires a SqlClr context, which is only available when running in the Sql Server process". If i use pipe i don't know how to convert that to an int value. Any suggestions please....
As per this Blog post, try it like this, with the SQLConnection not in a using. The SQLCommand is Disposable and should be in a using though.
SqlConnection conn = new SqlConnection("context connection=true") ;
using(SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) AS 'Order Count' FROM customer_master with (nolock)", conn))
{
conn.Open();
return (int)cmd.ExecuteScalar();
}
I wrote the below first, but I think the above is the answer, I'm leaving struck out in case it is relevant.
A ContextConnection is a connection back down the existing open connection that the SQL calling the CLR function is using.
To use a SQL CLR Function with a ContextConnection you have to call it from inside a SQL Statement.
e.g. (where CLRConvert is my CLR function that connects back to my database and performs a query and converts stuff).
select dbo.CLRConvert(Data) from MyTables;
If you need to call it outside of here, you will need a proper connection string.

Using a View from SQL Server 2008 in C# & Asp.net

I have a C#/ASP.net project has included a database that I have developed that includes a nice and convenient View that would be handy to use.
I have the SQL connection setup to a SQL Server 2008 DB I created. It seems as though it is connecting fine, but I don't understand how to actually use the View that I created without hard coding the query into the program (been told this is bad sometimes?).
This is my connection I setup:
SqlConnection conn = null;
conn = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False");
conn.Open();
SqlCommand command = new SqlCommand(query, conn);
Basically, I need some code to query using this View. I can see the View and look at the results that would be obtained, but not access it in the program!
The view is named "UserView". Help is much appreciated!
You could use something like the following. But it's usually considered evil to put hardcoded SQL commands into .Net code. It's much better and safer to use stored procedures instead.
This should get you started. You can modify it to use stored procedures by
changing the command.CommandType to indicate it's a stored proc call
And adding the proper parameters to the command that your SP needs.
Change command.CommandText to the name of your SP, thus
eliminating the hardcoded SQL.
sample code below:
using (SqlConnection connection = new SqlConnection("Data Source=raven\\sqlexpress;Initial Catalog=ucs;Integrated Security=True;Pooling=False"))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * from your_view WHERE your_where_clause";
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// process result
reader.GetInt32(0); // get first column from view, assume it's a 32-bit int
reader.GetString(1); // get second column from view, assume it's a string
// etc.
}
}
}
}
Using VS2013 add a new DataSet to your project. Drag your View from the Server Explorer to the DataSet Design Surface.

Query Hangs

Ok, this seems simple but I can't find a solution to save my life. I am trying to do a very simple INSERT query on an Oracle DB. I can log into the DB in TOAD with the same credentials as I use in the code and run the INSERT with no problem, so as near as I can tell there are no permissions issues with the credentials and the query itself is syntacticly correct. When I try to run the below code, it just hangs. No errors or anything. I can see the session pop up in TOAD so as far as I can tell the code establishes the connection with no problem. Here is the code:
String connStr = "Data Source=DB;User id=<USER>;Password=<PASSWORD>;";
String query = "INSERT INTO table (fields) VALUES (values)";
OracleConnection conn = new OracleConnection(connStr);
conn.Open();
OracleCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
I have also tried using an ADO connection and got the same result. Any ideas are appreciated.
Have you committed or rolled back the transaction in Toad? Your application could be waiting on a lock held by your session created by Toad.
Have you tried wrapping it in a transaction and explicitly committing after the insert? IIRC, Oracle's default semantics are very transaction-oriented, unlike SQL Server's.

Categories