SQL Server :: Code For Simple Database Connection In 3.5?
Aug 8, 2010
.net frame work. I know about few controlin .net and I have tried few programs also. Now want to learn a databaseconnection in .net so please provide me one easy example of such program.
View 2 Replies
Similar Messages:
Nov 24, 2010
i bind a dropdownlist to a database and later on, on button click i connect to database to get some value in a label. My 1st part works fine but when i try to do the second part i get the error message as
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at _Default.Button1_Click(Object sender, EventArgs e) in c:Documents and SettingsaMy DocumentsVisual Studio 2008WebSitesoolbar1Default.aspx.cs:line 56
My code is:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
SqlConnection myConn = new SqlConnection("Server=localhost;Database=testcase;Integrated Security=SSPI");
SqlCommand myCmd = new SqlCommand("select skey,casecode from casetype", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList3.DataSource = myReader;
DropDownList3.DataTextField = "skey";
DropDownList3.DataValueField = "casecode";
DropDownList3.DataBind();
//Close the connection.
//myConn.Close();
//myReader.Close();
//Add the item at the first position.
DropDownList3.Items.Insert(0, "<-- Select -->");
}
catch (Exception ex)
{
Response.Write(ex.StackTrace);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection myConn1 = new SqlConnection("Server=localhost;Database=testcase;Integrated Security=SSPI");
SqlCommand myCmd1 = new SqlCommand("select casename,skey from casetype where skey=?", myConn1);
myConn1.Open();
SqlDataReader myReader1 = myCmd1.ExecuteReader();
String type = DropDownList3.SelectedItem.Text;
myCmd1.Parameters.AddWithValue("?", type);
}
catch (Exception exw)
{
Response.Write(exw.StackTrace);
}
}
}
View 3 Replies
Aug 4, 2010
I am a .net developer.I am not that strong in SQL.I need a simple query.This is from Northwind Database.
select 'Select All' as CustomerID,'Select All' as City union(select CustomerID, City from Customers
order by City)
i need to get output like 1st row should be Select ALl Select All and next rows should be output of this stat..(select CustomerID, City from Customers order by City)
i am not getting this...i can do by keeping the second query result in temp table and then using union... but i am looking without temp tables or simple query.
View 2 Replies
Feb 10, 2012
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$appSettings:ConnString%>"Â SelectCommand="sql query ............."
This is in design and with the above I have
 SqlDataSource1.SelectCommand = "sql query ............. " in code behind
but if i have the connection in code behind. How do I execute
SqlDataSource1.SelectCommand == "sql query ............. "
It without any reader or dataset...
View 1 Replies
Sep 10, 2010
How do we convert, the following code to query a SQL database with ASP using a DSN-less connection
[Code]....
View 2 Replies
Aug 13, 2010
This issues has been driving me nuts. I am trying to follow the tutorial on [URL] I am trying to connect to a database in Microsoft SQL Server 2008. The way I do this is by right clicking on the "Data Connections" > Add Connection. Afterwards the Add Connection window comes up, I make sure my data source is "Microsoft SQL Server (SqlClient). And, I choose a server name; the only server I can choose is DomainSQLEXPRESS. The issue is when I go down to the "Select or enter a database name" drop down box, I do not see my database listed. I have also made sure in the SQL Server Management Studio that I have given my user all the privileges for the database. I know my explanation is kind of vague, but would anyone know the reason why I would not see my database?
View 3 Replies
Mar 11, 2010
I recently started NOT putting code in separate file. I am using vb. I am having a problem with my database connection. The live code is working just fine....but when I try to debug locally. i get this error. connection to the database from my local visual studio is not working. A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" %>
<script runat="server">
Const ConnectionString As String = "Data Source=1234.database.com;Initial Catalog=database_name;Persist Security Info=True;User =user_name;Password=123456"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim MyConn As New Data.SqlClient.SqlConnection(ConnectionString)
Dim cmd As New Data.SqlClient.SqlCommand("Select count (*) from Classifieds where (ClassifiedCatagory = 'Antiques')", MyConn)
cmd.Connection.Open()
Dim count As Integer = cmd.ExecuteScalar() 'this contains the number of records
Label_Antiques.Text = count
cmd.Connection.Close()
View 4 Replies
Mar 2, 2010
i am adding a connection in asp.net using visual web developer to sql server database file, it's an MDF file.
when i click test connection i get this:
View 2 Replies
Oct 20, 2010
I devlopyed on asp.net application in IIS, i need to know how many current database connection is open for the database..
so how can i check how many connection are currently using for this database... if we dont want some connection how can we kill the connection
View 2 Replies
Mar 6, 2010
I've read several questions explaining how to handle file uploads in asp.net mvc. I am trying to submit both the file as well as form fields describing it. That might be the issue. I'll go write to the code:
View code:
<% using (Html.BeginForm("CreateFile", "Video", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
</p>
<p>
<label for="Password">Password:</label>
<%= Html.TextBox("Password")%>
<%= Html.ValidationMessage("Password", "*")%>
</p>
<p>
<label for="Description">Description:</label>
<%= Html.TextBox("Description")%>
<%= Html.ValidationMessage("Description", "*")%>
</p>
<p>
<label for="DateUploaded">DateUploaded:</label>
<%= Html.TextBox("DateUploaded")%>
<%= Html.ValidationMessage("DateUploaded", "*")%>
</p>
<p>
<label for="DateRecorded">DateRecorded:</label>
<%= Html.TextBox("DateRecorded")%>
<%= Html.ValidationMessage("DateRecorded", "*")%>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
<% } %>
Controller code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateFile(VideoDTO video, HttpPostedFileBase f) //[Bind(Exclude="VideoId")]
{
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Server.MapPath("Videos") + Path.GetFileName(hpf.FileName);
hpf.SaveAs(savedFileName);
video.FileName = hpf.FileName;
}
repository.CreateVideo(video);
return RedirectToAction("Index");
}
I've seen several examples, but haven't come across one that is trying to submit both a file and other form data. Some other things of note is other examples seem to not put a HttpVerb attribute on the action method at all and have an empty parameter string. The files I'm looking to accept will be video files of various types but they can be anywhere from 100-300 mb. The files I've attempted to use (locally) have been rather small comparatively (50 or so mb).I know it's been asked but I feel like my issue here is different somehow. When I submit the page I see:
The connection was reset
The connection to the server was reset while the page was loading.
View 2 Replies
Feb 9, 2011
My web server and database server are currently both in the same room. However, the web server might be changed to a different server in another building about a mile down the street. I want to make sure this doesn't have a negative impact on the connection speed between the database and web server. Is there a way to test the connection speed from both web servers to the database?
View 3 Replies
Jun 24, 2010
I am a beginner in using Asp.NET with C# and it is my first time I am trying to establish a connection with an SQL server 2005 database: Here is my simple code to connect to the sql server database,I am getting the text message set in the label. Is my problem in the connectionString ??? how to write it and ow to get the server name and write it correctly ....or how to specify the database name (all path or just database name??)
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server = Saher;Database=Database.mdf;integrated security = true");
try{
connection.Open();
}
catch{
lblMessage.Text = "COULDN'T CONNECT to Stupid database";
}finally{
connection.Close();
}
}
View 6 Replies
Dec 1, 2011
I have a simple .aspx page. Where I need to connect to sql server 2008 and show the records on the page in a gridviewcontrol. It will have Edit button on the gridview control. I am getting some weird message about the connection string.
Error message is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Keyword not supported: 'initial catalog'.
Web.config file:
Code:
<connectionStrings>
<add name="ConnectionString_SqlServer" connectionString="Data Source=PricingDB;Initial Catalog=DB1;Integrated Security=True;Connect Timeout=300" providerName="System.Data.SqlClient" />
</connectionStrings>
In the .aspx page this is how I am connecting.
Code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString_SqlServer %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="select name, value from dbo.Pricing order by name asc"
>
</asp:SqlDataSource>
View 2 Replies
Oct 14, 2010
i am using sqlserver 2008
in my computer, sql server name is "LOCALHOET-PC" AND SECOND ONE "LOCALHOST-PCSQLEXPRESS"
I have write a code in my software like
SqlConnection conn;
conn = new SqlConnection("Data Source=LOCALHOST-PC;Initial Catalog=n4netsALT;Integrated Security=sspi");
conn.Open();
and it is working working smoothly in my computer
View 2 Replies
Aug 2, 2010
To give some background details, I have created a website for a friend that has a few pages that require a database in the background. I've used Visual Studio templates for most of it, so there's the standard ASPNETDB.MDF file that's created for users and groups, a login page and a page to view and manage those users etc etc. The login page uses the standard controls for logging in, retrieving lost passwords and so on. Being standard controls, by default they get the connection string from the web.config file. Upon attempting to upload the site to my host (1and1.co.uk in case anyone else has any dealings with them) I discovered that storing the connectionstring doesn't work. 1and1 support say that the sql databases can only be accessed using scripts like this (this is an example of theirs):
<html>
<title>Queries from the MS-SQL database with ASP</title>
<body bgcolor="FFFFFF">
<h2>Query from table <b>products</b> with ASP</h2>
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.open "PROVIDER=SQLOLEDB;DATA SOURCE=mssqxxx.1and1.com;UID=dboxxxxxxxxx;PWD=xxxxxxxx;DATABASE=dbxxxxxxxxx"
'This code block will create a recordset
Set rs = Server.CreateObject("ADODB.Recordset")
SQL = "select * from products"
rs.open SQL, conn
'will iterate to display the records got from the database
While Not rs.EOF
response.write(rs("id") & " " & rs("price"))
rs.MoveNext
Wend
'closes the connection
rs.close
conn.close
Set rs = Nothing
Set conn = Nothing
%>
</body>
</html>
So my question, is it possible to get the standard asp.net controls to access a database through a script like this?
View 8 Replies
Aug 9, 2010
I have an asp.net web page which works with a database. When I first upload it I never disposed the connections so after using the different modules of the application for sometime it would suddenly stop working saying the connection pool filled or something like that.To fix it when a user clicked a button I opened the connection, tell the database what I needed and finally disposed the connection.
This seemed to fix everything, in fact you can work with application all you want, the problem comes if you stop using it for certain time.So for instance, I have a module in my webpage where user can capture information for a certain product. When the user clicks in one button the info gets into the database. If the user is continuosly capturing data everything works fine, but if it goes for about 10 min when he clicks the button he will receive an error. To fix this the user has to log-in again.
Every module opens a connection to the database to verify the user identity, but then after it verifies it I dispose the connection so I don't think there is a problem.
View 3 Replies
Jan 3, 2011
I have this following requirement.
My Web Application is hosted on Server A. My Database is hosted on Server B.
Server A and Server B are not on same network. How can i point my connection string to the database in this scenario? Can any one give an example for this kind of Connection String?
View 4 Replies
Nov 23, 2010
I just installed sql server 2008 R2 on my computer. I am trying to connect to sql server throught my C# code and everytime I run the C# program,
I get this error "A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) "
The connection string that I used in my web.config file is
[Code]....
I am not sure what am I doing wrong, but I followed this article below step by step and still I am getting the same error
http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/
My instance name is MSSQLSERVER and the server that I am using is on my local machine and it has my computer name in it.
View 10 Replies
Dec 16, 2010
I am retrieving connection string based on value stored in cookie.NowI am making crystal report. I cannot hard code server credential. I have to get these credential from connection string from web.config. so that i can pass these credentials to my crystal report .
ConnectionInfo reportConnectionInfo = new ConnectionInfo();
reportConnectionInfo.ServerName = connection string server name from web.config
reportConnectionInfo.DatabaseName = connection string database name from web.config
reportConnectionInfo.UserID = ...;
reportConnectionInfo.Password = ...;
View 1 Replies
Feb 4, 2010
My website is working but when I host it up, the connection are all screw up. Is it because my connectionString are all linked via SqlDatasource and is for local files only? Whats the coding that I need to put in so that my site will connect to the database via accessing the web.config or server?
View 11 Replies
Sep 5, 2010
I am having problem when i was trying to attach .mdf file while create a new connection of SQL server, create a new connection of SQL database file and open the database in Server Explorer. I am using VS 2010 Ultimate and SQL Express 2008 R2.
Here are the error message.
1. Attach .mdf in SQL database file and open the database in Server Explorer
2. Create a new SQL server and attach .mdf
View 5 Replies
Apr 1, 2011
using sql server 2005.
I have been directed to change logging on a database to "simple" mode.
how do you do this?
View 1 Replies
Feb 2, 2010
Background: I use SQL server 2005 developer edition and visual studio 2008. Visual studio 2008 is running on a local machine with Vista business edition. SQL server is running on a remote server using Windows server 2003. Both computers are within the same domain.
Problem: First, I used the server explorer to connect to the SQL server. Everything works as desired. Then I write code to do the same thing. I keep getting the following error message:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
However, I used the exactly identical connection string as the one used in the server explorer. So connection string should not be the problem. In addition, I tried the test code in MSDN, which tells whether my domainusername can flow the network. It turns out the user name is fine. I also went to the SQL server management studio and found the login for my computer is NVCWeihao while my computer login name is NVCweihao. I am wondering if this uppercase letter really affects the connection.
View 2 Replies
Jul 23, 2010
I am using VS2008 and oracle 10g ODP.Net. The oracle database that I used in the connection is working and tested it using sql plus.The connection string when used in a GriDView works perfectly. Now when I created a new listview control with the same connection it gives an error.Database schema could not be retrieved for this connection. Please make sure connection settings are correct and the database is online
Object reference not set to an instance of an object at VSDataObjectSupport (478,6)
View 2 Replies
Sep 30, 2010
I have VS 2010 professional. I am trying to open "ASP.Net Configuration" through Project -> ASP.Net Configuration.
It pops up the Notification about the ASP.Net Development Server localhost but doesn't open ASP.Net Configuration in the default browser.I clicked on the Root Url (by double clicking on the 'development server' at the right bottom from Notification Manager).
It throws following error
"An error was encountered. Please return to the previous page and try again."
Clicking on "How do i use this tool".It opened page with error.
Tool Has Timed Out
View 2 Replies