ExecuteReader requires an open and available sqlconnection.open。

查看:2408|回复:7
各位,麻烦帮忙解答一下:
& && & 我是用VS2010新建了一个website;在APP_CODE文件夹下,
新建了一个有关数据库操作的类SqlOperate.cs:
public class SqlOperate
public SqlOperate()
&&// TODO: Add constructor logic here
& && &&&//
& && && &this.strcon = ConfigurationManager.ConnectionStrings[&constr&].ConnectionS
&&&&public SqlConnection sqlcon()
& && &&&SqlConnection sqlcon = new SqlConnection(strcon);
//建立并返回SqlCommand对象
& & public SqlCommand sqlcom()
& && &&&sqlcon().Open();
& && &&&SqlCommand sqlcom = new SqlCommand();
& && &&&sqlcom.Connection = sqlcon();
& & public SqlCommand sqlcom(String strsql)
& && &&&sqlcon().Open();
& && & SqlCommand sqlcom = new SqlCommand(strsql,sqlcon());
然后在default.cs文件中调用它们:
protected void btSpecialty_Click(object sender, EventArgs e)
& && &&&if ((tbSpecialtyName.Text.Trim() == &&) || (tbSpecialtyRemark.Text.Trim() == &&))
& && && && &string str = &alert('专业名与专业描述不能为空');&;
& && && && &Page.ClientScript.RegisterClientScriptBlock(this.GetType(), &warning&, str, true);
& && &&&else
& && && &&& SqlOperate sql = new SqlOperate();
& && && && & sql.sqlcon().Open();
& && && && &string strsql = &select * from SpecialtyInfo where convert(varchar(255),SpecialtyName)='&+tbSpecialtyName .Text.Trim ()+&'&;
& && && && & if (sql.sqlcom(strsql).ExecuteScalar() != null)
& && && && &{
& && && && && & string str = &alert('该专业已存在,请重新起名');&;
& && && && && & Page.ClientScript.RegisterClientScriptBlock(this.GetType(), &warning&, str, true);
& && && && &}
& && && && &else
& && && && &{
& && && && && & string str2 = &insert into SpecialtyInfo (SpecialtyName,Remark) values ('&+tbSpecialtyName .Text .Trim ()+&','&+tbSpecialtyRemark .Text .Trim ()+&') &;
& && && && && & Specialty sp = new Specialty();
& && && && && & string str3 = sp.addSpecialty(str2);
& && && && && & str3= &alert('添加专业信息成功');&;
& && && && && & Page.ClientScript.RegisterClientScriptBlock(this.GetType(), &warning&, str3, true);
& && && && &}
& && && && &sql.sqlcon().Close();
运行时,出现问题:ExecuteScalar requires an open and available Connection. The connection's current state is closed.&&数据库的连接关闭了。但在上面红色代码中,有调用SqlOperate类的SqlConnection对象的返回方法来获得该对象,再用该对象的Open方法打开;
朋友们,请帮帮忙解答,谢谢。
不要在数据库访问过程中使用js交互。
引用:原帖由 oswica 于
11:11 发表
不要在数据库访问过程中使用js交互。 没有用JS,不知道是不是跟类的对象实例化方面有关,不清楚是不是Connection对象与Command对象的实例不同,导致Connection打开了,但不是Command对应的Connection打开;但后来采用SqlCommand sqlcom = new SqlCommand();
sql.sqlcom(strsql).Connection = sql.sqlcon();
也不能打开数据库连接。
string str = &alert('该专业已存在,请重新起名');&;
& && && && && &&&Page.ClientScript.RegisterClientScriptBlock(this.GetType(), &warning&, str, true);
这个难道不是?
引用:原帖由 oswica 于
13:39 发表
string str = &alert('该专业已存在,请重新起名');&;
& && && && && &&&Page.ClientScript.RegisterClientScriptBlock(this.GetType(), &warning&, str, true);
这个难道不是? 哦哦,是啊。后来把这段JS代码先注释掉,换成response输出;也依然出现这个问题,连接不了。
//建立并返回SqlCommand对象
& & public SqlCommand sqlcom()
& && &&&sqlcon().Open();
& && &&&SqlCommand sqlcom = new SqlCommand();
& && &&&sqlcom.Connection = sqlcon();
& & public SqlCommand sqlcom(String strsql)
& && &&&sqlcon().Open();
& && & SqlCommand sqlcom = new SqlCommand(strsql,sqlcon());
这2个方法有问题,sqlcon().Open();都已经打开了..sqlcon()这边又打开
换个写法就好了...
public SqlCommand sqlcom(String strsql)
& && &&&SqlConnection sqlcon = new SqlConnection(strcon);
& && &&&sqlcon.Open();
& && &&&SqlCommand sqlcom = new SqlCommand(strsql, sqlcon);
最简单就这样..调用就好了
引用:原帖由 promising123 于
23:27 发表
哦哦,是啊。后来把这段JS代码先注释掉,换成response输出;也依然出现这个问题,连接不了。 这样还是有交互的。
我意思是你将数据获取后在处理或者做判断。IDE :: Operator Requires Either Two Or Three Operands?
Oct 22, 2011
I am in need of help with a project which I am completing.This is what I am currently working with:
If RadioButton1.Checked = True And ComboBox2.Text = &Rate 1& Then Dim Rate(0 To 3) As String
Rate(0) = Math.Round(((85 + (TextBox2.Text - (150 * TextBox1.Text)) * 0.25) / 3) * 100, 0)
Rate(1) = Math.Round((85 + (TextBox2.Text - (150 * TextBox1.Text)) * 0.25) * 100, 0)
Rate(2) = 25
Rate(3) = &F& + TextBox2.Text
Similar Messages:
ADVERTISEMENT
Jan 27, 2010
I am tightening up my coding with the Option Strict set to ON.
It has now produced alot of errors.
An example of this is:If AllocatedDGV.Rows(i).Cells(&RoomNumber&).Value = RoomsAvailableDGV.Rows(j).Cells(&RoomName&).Value ThenIt gives me the following error: Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity.
Apr 6, 2012
I need to write an interface to get data to/from our data files.We have a low level class that holds field values for each record read from the files.This just holds two values, the value read from the file (DBValue) and the updated value that may need to be written back to the file (CurrentValue).These values may be any of the standard value types (integer, date etc) or a string.Either value (DBValue or CurrentValue) may be null if not defined.I have written the class to manage this data which works fine while option strict is NOT on.But we have an office policy of having option strict on all the time.When I put option strict on, my object value comparisons fail with the error: "Option Strict On disallows operands of type Object for operator '='. Use the 'Is' operator to test for object identity."Question, how should I change the following code to handle option strict on ...This is all running on Visual Studio 2010[Code]...
Mar 4, 2012
First post here so Im sorry if im posting in the wrong place. Im trying to build a simple poker game which requires the program to recognise hands of each players. Luckily there are 3rd party solutions such as pokereval. However my problem comes when i try to convert a C# ported version of pokereval by Keith Rule, into vb.net. The following error shows up referring to the line with the *.[Code]...
Oct 7, 2010
Given this definition of an incoming byte array I get the following error.
Aug 4, 2009
Dim lastidcmd As New SqlCommand(&SELECT MAX(ProformaID) FROM & & IIf(boolException, &ImportException_Proforma&, &Proforma&) & & WHERE SupplierId=& & CustomerId & &;&, con)in the part marked in red I get this error:Error71Option Strict On prohibits operands of type Object for operator '&'.how can I fix this. I turned on Option Strict today and got this error.
Nov 21, 2010
When I try to write the following code, I get error message:Option Strict Disallows Operands of Type Object use IsHTML If dtrow.Item(&BathNew&) = 0 Thendtrow(&BathNew&) = dtrow.Item(&BathsTotal&)when I use Is I get the error message:Is requires operands the have reference typesIf dtrow.Item(&BathNew&) Is 0 Thendtrow(&BathNew&) = dtrow.Item(&BathsTotal&)End If
Mar 10, 2009
Possible Duplicate: Is there a conditional ternary operator in VB.NET?
Can we use Coalesce operator(??) and conditional ternary operator(:) in VB.NET as in C#?
Nov 11, 2009
I want to perform equality comparison in VB.NET and cannot get it to work. Error: value of type Boolean can not be converted to System.Drawing.PointF [code]...
May 25, 2010
A lot of my programs require the ability to write files to the hard drive. When I first made these programs for XP they worked great. Now I'm less ignorant about UAC (got a new laptop recently). And for future customers...I've noticed the potential for a LOT of annoying error messages....and quite frankly if the program can't write data to the hard drive or thumb drive it's on...there's no point to running it....I've tried multiple times to build in the manifest a requirement for administrator or user access....I'm not sure if anything less would solve the problem...but have failed because click-once has security features in place to prevent me from doing so.I'd rather not have to tell my customers how to make the program run as an administrator by editing the file's properties...I'd much rather have a convenient pop up like what you'd see new programs such as Itunes or Filezilla show if they were in conflict with UAC requesting the privileges they need.I'd really like to do this but have had little success.
Nov 23, 2010
My app needs to delete and rewrite a text file called events.txtnow it used to work but now when i run the app it shows an error due not being to access the file in the &Program FIles (x86)/MyApp/& folder?
Mar 13, 2012
I am trying to create a small program that checks [URL] for a work order every minutes. While I don't know of any API that I can use, I think it would be easy enough to simply check the page and see if there are any new work orders listed. The question I have is how to access the work order page. Every a few minutes field nation logs you out of their website. At that point I am required to log back in again to access my account. How can I automate or bypass this process so that my program and regularly check for new workorders?
Sep 8, 2011
On a webpage they have a checkbox that has an onchange, assuming this is javascript from my past knowledge. However in VB.NET when i click this checkbox by id, name, or even class it doesn't trigger the onchange to tell there webpage that the box is checked.I'm assuming that i need to use javascript to tell the webpage that the checkbox is checked or somehow implement a browser or java itself into the webbrowser if that is the problem.Here's the HTML code:&td bgcolor=&#FFFFFF& class=&col2&&&input type=&checkbox& onchange=&updateCheckBox(this); validateNew('openAccountNewUserForm',this);& class=&check& name=&checkTermsOfUse& id=&checkTermsOfUse&& [Code].....
Jun 23, 2010
I have a datetimepicker on a form.
It is not bound to a table field.
When I open the form, I click on the arrow on the right of this control, the calender picker appears, I click on a date, and then I have to hit enter for the picker to close and the date to transfer to the control.After that, I can click on the arrow, click on another date, and the picker closes immediately and the date value goes into the control.
Why do I have to hit enter the first time?
I would like to be able to transfer the selected date to the screen the first time with just 1 click and without hitting enter.
Nov 19, 2009
Similar to the CSV file which can be downloaded from [url] . How can I downloada file which requires authentication? I can simply puter.Network.DownloadFile[url] To download the file which is available in public. I tried setting the username and password as per the MSDN documentation but all I get is the HTML content of the login page.
Jun 4, 2009
Public Class app_mainformDim mssqluname As StringDim mssqlpword As String[code].....
Jun 8, 2009
So, I'm using shell to start up an external application at the press of a button, but the application requires several other external files with it in order for it to work.
How could I make it work?
Note: I'm a newbie
Apr 2, 2010
If I create an application in VB.NET using Visual Studio 2008, what version of the .NET Framework do other people need to have in order to run my program?
Is it the same every time, or does it depend on what the application actually does?
Mar 10, 2010
I am trying to make a program in Visual Basic which requires the use of 24-bit strings. However, I am not aware of a common name for them. I know that Byte is 8-bit, and Short is 16-bit, so is there a name for 24-bit?If not, then is there any way to combine a Byte and a Short to create the needed 24-bit value in my program?
May 10, 2011
Update requires valid UpdateCommand passed DataRow collection modified rows. When I run the following code. But the strange thing is that I have similar code on another form and it works great. The only difference is the database table is different. I verified both tables and they look identical, as far as settings. I have verified that _Non_MS_Office_Licenses has a primary key that is unique. Looking in dataset manager I see the query for fillBy() is fine and it has all the insert and update stuff. At the end when it verifies it says all is verified when I configure the datasetDim row = FrmApp.Non_MS_Office_LicensesBindingSource.Currentrow(&Primary User&) = Replace(CStr(TxtUserid.Text), &'&, &`&)row(&Staff Last Name&) = Replace(CStr(TxtLastName.Text), &'&, &`&)row(&Staff First Name&) = Replace(CStr(TxtFirstName.Text), &'&, &`&)[Code]...
Jan 1, 2012
I have a question to ask you. All of the programs that I made always worked perfectly in my PC. But, whenever I test it on another PC, it requires a thing like... Microsoft .NET Framework Version 4. Which is really annoying, cuz that thing installs in 15 minutes. I mean, can I do something about this? Is this common?
May 18, 2010
I created a new project added a form and on the form added a button. The click event of the button contains only 5 lines of code. (thats all , apart from this nothing i did to the project)
Jul 13, 2011
I can't fix following code:Private Sub Dic_List(ByRef sender As Array)Dim L_sender As IntegerL_sender = sender.Length / 5 - 1ReDim Preserve sender(4, L_sender + 200)End SubError 1 'Redim' statement requires an array.But sender is an array.
Aug 3, 2011
I am trying to over come this paoblem from last 2 days But i am not able to overcome.I was able to set up the environment so that I can call .NET method (via COM) from a classic ASP page.Everything actually works as intended until when I have to call a .NET method that requires a .NET type.So I have a method named SetTable Like Below I have a function like this in .NetPublic Sub SetTable(ByVal _City As City, ByVal _Country As Country)'doing some thingEnd Suband i have asp code like this:dim CountryUtil, City, Countryset CountryUtil= Server.CreateObject(&mydll.CountryUtil&)set City= Server.CreateObject(&mydll.City&)[code]....' I get this error here:'Microsoft VBScript runtime error '800a; 'Invalid procedure call or argument: 'SetTable'
Nov 22, 2010
The programing I am creating requires window captions for SendKeys.
Some windows hide their captions and I want to be able to use Spy++ or create my own way of getting the caption.
All I want from Spy++ is Finder Tool, is there anyway of just taking that from Spy++ or how would I go about creating it?
Jun 21, 2010
i want to download a file from a SSL web to my local(C:)[URL]Scenario: from the web browser(Internet Explorer), i required to login to the site in order to download the file.in the vb program i pass in this url to download the file (include my password and username): [URL] but what has been downloaded to my C: is the login page(in myfile.txt) but when i use the url on the web browser[URL] i managed to get the file (the actual file).Question: is there anyway that i can download the file from a login page?
Oct 11, 2010
Public Sub Procedure(ByVal procname As String, Optional ByRef param() As SqlParameter = Nothing)'Execute Store Proc In Database Dim cmd As SqlCommandcmd = New SqlCommand(procname, conn)mandType = CommandType.StoredProcedure[Code]....I have came out with a simple DAL, when i pass in stored procedure and param, it throw me exception as the following&ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.&
Nov 20, 2009
I am hoping one of you experts/professionals might have a solution for me.I have an excel spreadsheet that requires 4 different criteria to compute a value.I wanted to be able to display 4 fields to a user then when the user submits that information, sends it to the excel spreadsheet which does the computations and then returns the value...The Thing is this excel spread sheet contains privatre data so it cannot be made public.
Mar 14, 2012
i'm a .net programmer, using .net framework 4, and i have a question about WithEvents clause.
Private Sub mylist_AddingNew(ByVal sender As Object, ByVal e As AddingNewEventArgs) Handles mylist.AddingNew..i get this error: Handles clause requires a WithEvents variable defined in the containing type or one of its base types.I think the problem is my custom bindinglist class....but how can i solve this?
Jul 7, 2010
I need to map a network drive from within a .NET application. I'm going to need to use an AD Username and Password to authenticate. Usually I just use a batch file with the net use command. How do I do this from within C# or VB.NET code?
Copyrights 2005-15 , All rights reservedc# - ExecuteReader requires an open and available Connection. The connection's current state is connecting. in execute reader - Stack Overflow
to customize your list.
Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
J it only takes a minute:
This question already has an answer here:
Here i use my webmethod.But when i going to connect it shows this error.But my code is good i think.
ExecuteReader requires an open and available Connection. The connection's current state is connecting.
public static List&CommonPages& GetCommonPagesDescription(int Type)
List&CommonPages& CommonPageDescription = new List&CommonPages&();
SqlCommand comGetAllFiles = new SqlCommand("GetCommonPageDescriptions", conDB);
mandType = CommandType.StoredP
if (conDB.State == ConnectionState.Closed)
conDB.Open(); // &-- Debugger Skip this & goto next line
comGetAllFiles.Parameters.Add("@Type", SqlDbType.Int);
comGetAllFiles.Parameters["@Type"].Value = T
SqlDataReader rdr = comGetAllFiles.ExecuteReader();//&-- error generating here
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
CommonPageDescription.Add(new CommonPages
Id = (int)r["Id"],
Description = r["Description"].ToString(),
Type = (int)r["Type"],
UpdatedDate = (DateTime)r["UpdatedDate"],
UpdatedBy = (Guid)r["UpdatedBy"]
catch (Exception ee)
conDB.Close();
return CommonPageD
conDB Initialized here
static SqlConnection conDB = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
1,43272446
marked as duplicate by ,
&asp.net badge can single-handedly close
questions as duplicates and reopen them as needed.
This question has been asked before and already has an answer. If those answers do not fully address your question, please .
Instead of opening the connection when it is closed, try to open the connection when it is not opened.
public static List&CommonPages& GetCommonPagesDescription(int Type)
List&CommonPages& CommonPageDescription = new List&CommonPages&();
SqlCommand comGetAllFiles = new SqlCommand("GetCommonPageDescriptions", conDB);
mandType = CommandType.StoredP
if (conDB.State != ConnectionState.Open)
conDB.Open(); // &-- Debugger Skip this & goto next line
comGetAllFiles.Parameters.Add("@Type", SqlDbType.Int);
comGetAllFiles.Parameters["@Type"].Value = T
SqlDataReader rdr = comGetAllFiles.ExecuteReader();//&-- error generating here
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
CommonPageDescription.Add(new CommonPages
Id = (int)r["Id"],
Description = r["Description"].ToString(),
Type = (int)r["Type"],
UpdatedDate = (DateTime)r["UpdatedDate"],
UpdatedBy = (Guid)r["UpdatedBy"]
catch (Exception ee)
conDB.Close();
return CommonPageD
conDB must be a shared connection?
Probably not a good idea, leverage connection pooling.
To fix it, consider opening and closing a connection per request.
Don't care if the voodoo sayers that this inefficient, in truth you want to open/close connections as little as possible but sometimes you need to go to the DB for a single reason.
There are ways you could share a connection better, using a context pattern for example.
But to solve your immediate problem structure your DB calls this way.
using( mon.DbConnection conn = CreateConnection() )
//create your command...
//create your reader/or execute your command...
10.6k11325
Not the answer you're looking for?
Browse other questions tagged
rev .24801
Stack Overflow works best with JavaScript enabled}

我要回帖

更多关于 sqlconnection.open 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信