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.
Related
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.
I'm trying to insert data into a Microsoft Access Database.
I inserted data into the Access database, but the first and second time are the only times that show the data I inserted. When I rebuild my application, the data I inserted is gone. I don't know where they go and not show. I use C# with the .NET framework to develop. Here's the relevant part of the code:
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
OleDbCommand com = new OleDbCommand();
com.Connection = con;
com.CommandText = "Insert into Language(English,Type,Thai) values(#eng,#type,#thai)";
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
con.Open();
com.ExecuteNonQuery();
I wrote that code, but I think it is strange. It doesn't show any errors or exceptions, but my data is not inserted correctly. Is this the correct way to insert data? If so, why it it not getting inserted?
When I rebuild my application, the data I inserted is gone
I suspect your database is being overwritten when the application is rebuilt.
This can happen, for example, if your application contains an MDB file that is copied to the output directory on build, and is used from the output directory.
I think Language should be a reserve word and you should wrap it in [] brackets.
Also consider wrapping the code in using blocks, like
using (OleDbConnection con = new OleDbConnection(...))
{
using (OleDbCommand com = new OleDbCommand(sqlString, con))
{
//code
}
}
Other than this [possible issue with table name and that you are not closing your connection], I don't see anything wrong with the code.
You define parameters for the query, but I don't see anywhere those parameters are bound to actual data...
Try some simple tests that replace the variables you're passing in as parameters with actual values, so you can isolate the problem:
In other words, replace this:
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
With something like this:
//I don't know the data types of your fields, so I'm guessing
com.Parameters.AddWithValue("#eng", "Test1");
com.Parameters.AddWithValue("#type", myEnum.Latin);
com.Parameters.AddWithValue("#thai", "Test1a");
If that works, then your problem probably lies with the english, type, and thai variables and you'll want to make sure they're getting the data you think they should be getting.
May be ur connection string not correct you can it by using .udl file
just follow the link
http://www.gotknowhow.com/articles/test-a-database-connection-string-using-notepad
You can also check the code shown below
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\ruby\\Desktop\\screenShots\\ruby.mdb;Persist Security Info=False");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into raj(Name,Roll) values('XYZ',12);",con);
cmd.ExecuteNonQuery();
I have a bit of .NET code that retrieves the results from an Oracle Stored Procedure, using the ADO.NET Library, and populates the results into a DataTable like so:
using System.Data.OracleClient;
public DataTable getData()
{
OracleConnection conn = new OracleConnection("Data Source=DATASOURCE;Persist Security Info=True;User ID=userID;Password=userPass;Unicode=True;Min Pool Size=1;Max Pool Size=20;Connection Lifetime=300");
DataTable dt = new DataTable();
conn.Open();
try
{
OracleCommand oraCmd = new OracleCommand();
oraCmd.Connection = conn;
oraCmd.CommandText = "stored_procedure.function_name";
oraCmd.CommandType = CommandType.StoredProcedure;
oraCmd.Parameters.Add("cursor", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataAdapter oraAdapter = new OracleDataAdapter(oraCmd);
oraAdapter.Fill(dt);
}
finally
{
conn.Close();
return dt;
}
}
This code has been working without any issues on several projects I have implemented the code on. However I am running into an issue on a new project, where the Oracle DB machine is actually much slower to respond, and seems to become unresponsive when too many clients begin to access the hardware. What I would like to do is implement some sort of timeout on the oraAdapter.Fill command - as it appears that when the database becomes unresponsive, the .NET application will hang on the 'Fill' method for as long as 10 minutes or more, never reaching the 'finally' codeblock and closing the DB connection.
I am in an environment where I am restricted to using the MSDN Library for connecting to the Oracle Database, so I'm hoping I can do it using the ADO.NET Control.
The CommandTimeout property does not work using the System.Data.OracleClient .NET 3.5 Provider. It appears that this functionality is not supported without the use of an external library.
It seems you need the CommandTimeout property, not ConnectionTimeout.
I want to load the entire database (SQL Server) I have into a dataset so that I can work with several tables and their relationships. I know this might be frowned upon, but how can I do this (I will be using DataRelation and Table objects)?
Thanks
Unless I'm missing something this should just be a simple case of generating a dataset and then altering the Fill methods to remove the WHERE portion. Then ensure you call the fills in the right order (master, then detail) to ensure you maintain the referential integrity.
You can run this... but don't expect to have a db or app server after.
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
using (SqlCommand command = new SqlCommand("exec sp_msforeachtable 'select * FROM ?'", conn))
{
conn.Open();
DataSet ds = new DataSet();
command.Fill(ds);
}
}
Read some article about in memory Database.
# Randolph Potter idea is an option - you can get the list of tables from the server, and then iterate on the list and load all the tables. I guess you can do that same about FK and relations.
you can probably do it automatically using the designer - using drag and drop from the server explorer to a dataset (VS2008), and with a little code load the entire thing into memory.
I suppose you could do multiple selects within a single stored procedure and then fill a dataset.
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
using (SqlDataAdapter command = new SqlDataAdapter("usp_YourStoredProcedure", conn))
{
command.CommandType = CommandType.StoredProcedure;
conn.Open();
DataSet ds = new DataSet();
command.Fill(ds);
}
}
I would agree with the other comments here that unless your database is tiny this is a really bad idea.
Basically, I would like a brief explanation of how I can access a SQL database in C# code. I gather that a connection and a command is required, but what's going on? I guess what I'm asking is for someone to de-mystify the process a bit. Thanks.
For clarity, in my case I'm doing web apps, e-commerce stuff. It's all ASP.NET, C#, and SQL databases.
I'm going to go ahead and close this thread. It's a little to general and I am going to post some more pointed and tutorial-esque questions and answers on the subject.
MSDN has a pretty good writeup here:
http://msdn.microsoft.com/en-us/library/s7ee2dwt(VS.71).aspx
You should take a look at the data-reader for simple select-statements. Sample from the MSDN page:
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
}
It basicly first creates a SqlConnection object and then creates the SqlCommand-object that holds the actual select you are going to do, and a reference to the connection we just created. Then it opens the connection and on the next line, executes your statements and returns a SqlDataReader object.
In the while-loop it then outputs the values from the first row in the reader. Every time "reader.Read()" is called the reader will contain a new row.
Then the reader is then closed, and because we are exiting the "using"-secret, the connection is also closed.
EDIT: If you are looking for info on selecting/updating data in ASP.NET, 4GuysFromRolla has a very nice Multipart Series on ASP.NET 2.0's Data Source Controls
EDIT2: As others have pointed out, if you are using a newer version of .NET i would recommend looking into LINQ. An introduction, samples and writeup can be found on this MSDN page.
The old ADO.Net (sqlConnection, etc.) is a dinosaur with the advent of LINQ. LINQ requires .Net 3.5, but is backwards compatible with all .Net 2.0+ and Visual Studio 2005, etc.
To start with linq is ridiculously easy.
Add a new item to your project, a linq-to-sql file, this will be placed in your App_Code folder (for this example, we'll call it example.dbml)
from your server explorer, drag a table from your database into the dbml (the table will be named items in this example)
save the dbml file
You now have built a few classes. You built the exampleDataContext class, which is your linq initializer, and you built the item class which is a class for objects in the items table. This is all done automatically and you don't need to worry about it. Now say I want to get record with the itemID of 3, this is all I need to do:
exampleDataContext db = new exampleDataContext(); // initializes your linq-to-sql
item item_I_want = (from i in db.items where i.itemID == 3 select i).First(); // using the 'item' class your dbml made
And that's all it takes. Now you have a new item named item_I_want... now, if you want some information from the item you just call it like this:
int intID = item_I_want.itemID;
string itemName = item_I_want.name;
Linq is very simple to use! And this is just the tip of the iceberg.
No need to learn antiquated ADO when you have a more powerful, easier tool at your disposal :)
Reads like a beginner question. That calls for beginner video demos.
http://www.asp.net/learn/data-videos/
They are ASP.NET focused, but pay attention to the database aspects.
topics to look at:
ADO.NET basics
LINQ to SQL
Managed database providers
If it is a web application here are some good resources for getting started with data access in .NET:
http://weblogs.asp.net/scottgu/archive/2007/04/14/working-with-data-in-asp-net-2-0.aspx
To connect/perform operations on an SQL server db:
using System.Data;
using System.Data.SqlClient;
string connString = "Data Source=...";
SqlConnection conn = new SqlConnection(connString); // you can also use ConnectionStringBuilder
connection.Open();
string sql = "..."; // your SQL query
SqlCommand command = new SqlCommand(sql, conn);
// if you're interested in reading from a database use one of the following methods
// method 1
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
}
// make sure you close the reader when you're done
reader.Close();
// method 2
DataTable table;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
// then work with the table as you would normally
// when you're done
connection.Close();
Most other database servers like MySQL and PostgreSQL have similar interfaces for connection and manipulation.
If what you are looking for is an easy to follow tutorial, then you should head over to the www.ASP.net website.
Here is a link to the starter video page: http://www.asp.net/learn/videos/video-49.aspx
Here is the video if you want to download it: video download
and here is a link to the C# project from the video: download project
Good luck.
I would also recommend using DataSets. They are really easy to use, just few mouse clicks, without writing any code and good enough for small apps.
If you have Visual Studio 2008 I would recommend skipping ADO.NET and leaping right in to LINQ to SQL
#J D OConal is basically right, but you need to make sure that you dispose of your connections:
string connString = "Data Source=...";
string sql = "..."; // your SQL query
//this using block
using( SqlConnection conn = new SqlConnection(connString) )
using( SqlCommand command = new SqlCommand(sql, conn) )
{
connection.Open();
// if you're interested in reading from a database use one of the following methods
// method 1
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index
}
// make sure you close the reader when you're done
reader.Close();
// method 2
DataTable table;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
// then work with the table as you would normally
// when you're done
connection.Close();
}