0

在我的站点中,我试图遍历列表视图并将信息插入到我的数据库中。但是,当我运行该站点时,我得到

无法打开用户默认数据库。登录失败。用户登录失败......(我的用户名)

唯一的事情是,在我有一个插入命令的另一个页面上,它工作正常,并且我能够毫无问题地访问数据库中的数据。

我尝试使用的代码是:

Guid InsertID = System.Guid.NewGuid();
        String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
        var myConnection = new SqlConnection(connectionString);

        SqlCommand insertCMD = new SqlCommand("INSERT INTO Orders (Order_ID, Item_ID, QTY, Price_Per_Unit, Total_Price) VALUES (@Order_ID, @Item_ID, @QTY, @Price_Per_Unit, @Total_Price)", myConnection);
        insertCMD.Connection.Open();

        foreach (ListViewItem item in ItemLV.Items)
        {
            TextBox QTY = (TextBox)item.FindControl("QTYTB");
            int InsertQTY = int.Parse(QTY.Text);

            if (InsertQTY > 0)
            {
                Label Price = (Label)item.FindControl("PriceLabel");
                HiddenField ItemID = (HiddenField)item.FindControl("IDHF");

                Decimal InsertPrice = Decimal.Parse(Price.Text.Substring(1));
                Guid InsertItemID = Guid.Parse(ItemID.Value);
                Decimal InsertTotalPrice = InsertPrice * InsertQTY;

                insertCMD.Parameters.Clear();
                insertCMD.Parameters.AddWithValue("@Order_ID", InsertID);
                insertCMD.Parameters.AddWithValue("@Item_ID", InsertItemID);
                insertCMD.Parameters.AddWithValue("@QTY", InsertQTY);
                insertCMD.Parameters.AddWithValue("@Price_Per_Unit", InsertPrice);
                insertCMD.Parameters.AddWithValue("@Total_Price", InsertTotalPrice);

                try
                {
                    insertCMD.ExecuteNonQuery();
                }
                catch
                {
                    Response.Redirect("~/Order/Error.aspx");
                }
                finally
                {

                }
            }
        }

        insertCMD.Connection.Close();

此代码向我抛出了上面概述的错误,但是,在我的注册页面上(使用与此相同的代码减去“foreach”循环并使用不同的命令和参数),它可以正常工作。因此,我假设这与我的用户无法访问数据库无关,而可能是我的代码有问题。

堆栈跟踪如下:

[SqlException (0x80131904): 无法打开用户默认数据库。登录失败。用户(我的用户帐户)登录失败。]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException 异常,布尔 breakConnection,操作1 重试,DbConnectionOptions userOptions,DbConnectionInternal& 连接)+78 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource 1 retry, DbConnectionOptions userOptions) +143 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83 System.Data.SqlClient.SqlConnection.Open() +96 Order_Order.ContinueBTN_Click(Object sender, EventArgs e ) 在 m:\OrderingSystem\Order\Order.aspx.cs:361 wrapCloseInAction) +5295167 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +889
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +225
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource

1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +167
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource



System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553594
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI。 IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35 System.Web.UI.Page。 ProcessRequestMain(布尔includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)+1724

编辑:

我的 web.config 文件中的连接字符串是:

<connectionStrings>
    <clear />
    <add name="LocalSqlServer" connectionString="Data Source=.\WebSite2013;AttachDbFilename=|DataDirectory|\Ordering_System_Database.mdf;Integrated Security=True;User Instance=True"
      providerName="System.Data.SqlClient" />
    </connectionStrings>

我的注册页面上的工作代码是:

    String connectionString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
                        var myConnection = new SqlConnection(connectionString);

SqlCommand insertUser = new SqlCommand("INSERT INTO Customer_Profiles(UID, First_Name, Last_Name, State_ID, Country_ID, Phone_Number, Mobile_Number, Date_of_Birth) VALUES(@UID, @First_Name, @Last_Name, @State_ID, @Country_ID, @Phone_Number, @Mobile_Number, @Date_of_Birth)", myConnection);
                                insertUser.Parameters.AddWithValue("@UID", newUserGuid);
                                insertUser.Parameters.AddWithValue("@First_Name", FirstNameTB.Text);
                                insertUser.Parameters.AddWithValue("@Last_Name", LastNameTB.Text);
                                insertUser.Parameters.AddWithValue("@State_ID", StateDDL.SelectedValue);
                                insertUser.Parameters.AddWithValue("@Country_ID", CountryDDL.SelectedValue);
                                if (PhoneTB.Text.Length > 0)
                                {
                                    insertUser.Parameters.AddWithValue("@Phone_Number", PhoneTB.Text);
                                }
                                else
                                {
                                    insertUser.Parameters.AddWithValue("@Phone_Number", DBNull.Value);
                                }
                                if (MobileTB.Text.Length > 0)
                                {
                                    insertUser.Parameters.AddWithValue("@Mobile_Number", MobileTB.Text);
                                }
                                else
                                {
                                    insertUser.Parameters.AddWithValue("@Mobile_Number", DBNull.Value);
                                }
                                insertUser.Parameters.AddWithValue("@Date_of_Birth", BirthDay);
                                try
                                {
                                    insertUser.Connection.Open();
                                    insertUser.ExecuteNonQuery();
                                    insertUser.Connection.Close();

                                }
                                catch
                                {
                                    Response.Redirect("~/Error.aspx");
                                }
                            }

从那以后,我做了一些实验并添加了测试选择和插入查询,发现似乎只有这个页面才会发生错误,无论我使用什么查询,但在我网站的所有其他页面上它都可以正常工作.

4

1 回答 1

1

感谢那些提供帮助的人,我设法确定问题实际上是我的 ListViews 使用的连接字符串 - 它是将我的数据库作为本地数据库附加,而不是像在 web.config 文件中那样使用我的服务器实例。

对于将来遇到此问题的任何人,请检查您的页面上实现的任何 SqlDataSources 是否使用与您的 web.config 文件中相同的连接字符串 - 我现在已经这样做了:

ConnectionString="<%$ ConnectionStrings:LocalSqlServer %>"

而且您能够判断它是否与页面有关而不是与数据库有关的方式是因为它只会发生在一个页面或某些页面上(就像它对我所做的那样)。

于 2013-06-23T02:31:04.673 回答