I am very new to ASP.NET. I have Visual Studio Express 2013 and MSSql Server that contains a bunch of databases. I watching a few tutorials about MVC/Entity framework to retrieve data from a table and display it. However, it is using Linq to SQL which I am not familiar with. All I need is to write a sql query to combine information in two tables and display it in the view. I could not find this simple tutorial on the internet. Can anyone give me a hint please?
To run a simple query you need to create a connection to the database like following:
var connection = new SqlConnection("your connecting string");
Once you have that you can connect to database and query using something called SqlCommand like following:
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection);
connection.Open();
//fetches the data by executing the command
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//You can process data here , read it from reader and process it
// the index 0 and 1 indicate your query columns
var somedata = reader.GetInt32(0) + reader.GetString(1));
}
}
else
{
//no data returned from query
}
reader.Close();
}
Related
I know of two ways to display data on a website.
The first is by using adding a DB connection to the Server Explorer and then dragging the table you want to display on the webpage. Visual Studio does all the backend stuff for you.
The second is where you just choose the control you want to use and you hook it up manually through code for it to display the data you want. You do not have to connect to the DB in server explorer. Something like this in code behind:
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("RawToSummary", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SDate", SqlDbType.Date).Value = MySDate;
command.Parameters.Add("#EDate", SqlDbType.Date).Value = MyEDate;
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Close();
private DataTable FillData(string connString, SqlCommand cmd)
{
SqlConnection conn = new SqlConnection(connString);
DataTable dt = null;
try
{
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds, "tableName");
dt = ds.Tables["tableName"];
}
catch (Exception e)
{
WriteLog("Error: " + e);
}
finally
{
conn.Close();
}
return dt;
}
I have 2 questions:
1) What is the second method called? I am trying to learn more about it but need a Google search term for it.
2) What are the pros and cons of each method?
I am using the following: Visual Studio 2010, SQL Server Management Studio 2008
Server Explorer/Database Explorer is the server management console for Visual Studio. Use this window to open data connections and to log on to servers and explore their system services.
With Server Explorer/Database Explorer we can view and retrieve information from all of the databases connected to. like:
List database tables, views, stored procedures, and functions
Expand individual tables to list their columns and triggers
Right-click a table to perform actions, such as showing the table's
data or viewing the table's definition, from its shortcut menu.
Programmatic approach
Second approach is the programmatic approach to perform the DM (data manipulation) and DD (data definition) functions.
Server Explorer/Database Explorer goes through the same course (connecting with database, query tables etc.) but in the background while in programmatic approach we write commands (queries/stored procedures) for the same.
I hope this gives an idea.
I'm having my app make a AJAX request for records from a SQL Server 2008 DB, by using .NET to handle the server side code. Currently, everything is being returned in DOM elements <Products> and <Product>, but I'd rather get the records fed into an array on the server-side, so when the response is sent, I can't just loop through them on my client side and manipulate as needed. I created the code below from another online resource doing the same thing, but he wanted his in the DOM Products elements (I'm a JavaScriptStack developer, so excuse my nativity).
.Net Code:
{
// 1. Initialize XML Response
Response.ContentType = "text/xml";
if (Request.HttpMethod.ToUpper() == "GET")
{
// 2. Open connection & Create command
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
// Select all by default (Unless there is an ID)
command.CommandText = #"SELECT *****(Hidden)";
// 3. Format XML as needed
// - Use <Products> as document element
// - Use <Product> as the record name
DataSet set = new DataSet("Products");
set.Tables.Add(new DataTable("Product"));
DataTable table = set.Tables[0];
try
{
// 4. Get Database content into DataTable
connection.Open();
SqlDataReader reader = command.ExecuteReader();
table.Load(reader, LoadOption.Upsert);
} catch (Exception ex) {
// Handle exception
writer.WriteLine(#"<Error>" + ex.Message + "</Error>");
}
// 5. Render XML Output
table.WriteXml(writer);
}
}
}
}
}
Note: Excuse the incorrect SQL statement, I don't feel comfortable posting our actual query on SO
I have written a code in ASP.NET to fetch data from Oracle database. The code returns data from locally hosted Oracle DB but when I am pointing towards the remote OracleDB, nothing comes. However, if I run same query on the remote DB using SQL Developer Tool, it works fine.
I have debugged my code for right SQL statement and it is absolutely correct.
Following is my code snippet
using (Oracle.DataAccess.Client.OracleConnection con = new
Oracle.DataAccess.Client.OracleConnection())
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["ca_eFormsVSED"].ConnectionString;
con.Open();
// query for fetch username and market
String sql = "a valid query"
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand(sql, con);
cmd.CommandType = CommandType.Text;
if (con.State == ConnectionState.Open)
{
Oracle.DataAccess.Client.OracleDataReader dr = cmd.ExecuteReader();
}
if (dr.Read())
{
//Do Something
}
}
Please suggest how to make it work.
I got the solution of this problem and it may help some one else. If you are 100% sure that code is correct and current SQL statement returns data from database, then check carefully your database tables have dependency or not. Remove existing tables and import new data again and it works fine for me.
over the past week or so I've been building an ASP site that connects to a Sql-Server 2008 database. I've never used Stored procedures and I was wondering if anyone could give me some guidance on how to create and how to use them within an ASP method. I'm trying to make the code of the website as simple and elegant as possible. Here's the code I'm trying to change into a stored procedure:
private void ExecuteInsert(string name, string type)
{
SqlConnection conn = new SqlConnection(GetConnectionStringHM());
string sql = "INSERT INTO tblSoftwareTitles (SoftwareName, SoftwareType) VALUES "
+"(#SoftwareName,#SoftwareSystemType)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[2];
//param[0] = new SqlParameter("#SoftwareID);
param[0] = new SqlParameter("#SoftwareName", SqlDbType.NVarChar, 200);
param[1] = new SqlParameter("#SoftwareType", SqlDbType.Int);
param[0].Value = name;
param[1].Value = type;
for (int i= 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg ="Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
This is just a Simple insert that takes two parameters from an entry form and inserts them into the database. Any Help with this would be much appreciated as I feel it would be a useful thing to know later on down the line. Thanks in advance!
You should look in to MSDN basics: http://msdn.microsoft.com/en-us/library/bb896274.aspx
You don't need to complicate things using for loop.
try
{
sqlConnection = new SqlConnection(dbConnectionString);
SqlCommand command = new SqlCommand(sql, sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SoftwareName", SqlDbType.NVarChar, 200).Value = SoftwareNameHere;
command.Parameters.Add("#SoftwareType", SqlDbType.Int).Value = SoftwareTypeHere;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine("SQL Error" + ex.Message.ToString());
return 0;
}
finally
{
conn.Close();
}
If you are using .NET 3.5 or above, you can use the USING code block which takes care of the disposal of your resources. I am not entirely sure, but from what I remember this was introduced with .NET 3.5 to replace Try/Finally code block (which required developers to dispose the resources like connection object manually through code).
using (SqlConnection con = new SqlConnection { dbConnectionString })
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand { CommandType = CommandType.StoredProcedure, Connection = con, CommandTimeout = 300, CommandText = "sp_Test" })
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#SoftwareName", SqlDbType.NVarChar, 200).Value = SoftwareNameHere;
command.Parameters.Add("#SoftwareType", SqlDbType.Int).Value = SoftwareTypeHere;
command.ExecuteNonQuery();
}
}
catch(SqlException ex)
{
//ex.ToString message here;
}
}
The answer you're looking for is at this SO post...
https://stackoverflow.com/a/4561443/1246574
The one thing I would improve upon for the accepted answer in that post, is the example in that answer doesn't use any USING statements. It would be better to have the connection and command within USING statements so they are automatically disposed.
Another approach would be to use the Microsoft Enterprise Library for interacting with your SQL Server DB. I think it's easier than using plain old SqlConnection and SqlCommand.
Since your code already uses parameters, you are 90% of the way there. All you have to do is:
Put the insert statement into a stored procedure, keeping the same parameter definitions as the dynamic statement.
Change CommandType.Text to CommandType.StoredProcedure
Change the command text to be just the name of the stored procedure.
Having done some reading on the subject I've come across some useful articles that really do question my need for stored procedures.
This article gives a good Viewpoint on how stored procedures can be more of a hassle than a help and are quite clunky and tedious in terms of coding, debugging ad error reporting.
http://www.codinghorror.com/blog/2004/10/who-needs-stored-procedures-anyways.html
And this article (linked in the one above) gives a good explanation on parametrized, explaining why they are necessary to reduce the risk of sql injections and also raises the point that these parametrized queries are cached in a similar way to procedures, giving them comparable performance gains
http://www.uberasp.net/getarticle.aspx?id=46
I feel that In my situation keeping parametrized sql Queries coded into my ASP pages will be the smartest move as these pages will be stored on a server and accessed by clients. I imagine if this were an application installed on several client machines hard coding the SQL wouldn't be a desirable option and so Stored procedures would be the best way to go (to my knowledge)
A follow Up to Stored procedures verses Parametrized sql can be found here with different links to each side of the argument if those are interested.
http://www.codinghorror.com/blog/2005/05/stored-procedures-vs-ad-hoc-sql.html
Hope this little answer helps out anyone else considering using stored procedures over parametrized SQL and vice-versa
When I execute this code:
AdomdConnection con = new AdomdConnection("Data Source=MyServer;User ID=MyDomain\\MyUserName;Password=MyPassword");
con.Open();
con.ChangeDatabase("Analysis Services Project1");
I get this exception:
Either the user, MyDomain\MyUserName$, does not have access to the
Analysis Services Project1 database, or the database does not exist.
The database name comes from looking at the server using Microsoft SQL Server Management Studio. If I bring up the properties on the server and go to the security section, my account is listed as a Server administrator. While in management studio, I can see data sources, cubes and execute mdx queries fine.
Why can't do I get this exception in code?
whihc line causes the error?
I imagine you have to infor the catalog on your connection string. Try addind
Catalog=Analysis Services Project1
to your con string.
Also, Analysis Services Project1 seems to be the projects name? Are you sure this is the database name as well?
First
added the reference for Microsoft.AnalysisServices.AdomdClient.dll
strCon = "Data Source=DBserverServerName;Integrated Security=SSPI;Initial Catalog=DBName;";
AdomdConnection con = new AdomdConnection("connectionstring"); // connect DB con.Open(); AdomdCommand cmd = new AdomdCommand("MDX query", con); //query
AdomdDataReader reader = cmd.ExecuteReader(); //Execute query
while (reader.Read()) // read
{
Data dt = new Data(); // custom class
dt.Gender = reader[0].ToString();
dt.Eid = reader[1].ToString();
dt.salary = reader[2].ToString();
data.Add(dt);
}