[英]Connecting to SQL Server Express from C#
I'm trying to connect to a SQL Server database from C#, but keep get thrown by an exception: 我正在尝试从C#连接到SQL Server数据库,但总是被异常抛出:
System.Data.SqlClient.SqlException
when trying to
open()` the connection.when trying to
打开()连接when trying to
System.Data.SqlClient.SqlException。
I have created a simple web form, with two text boxes: usernameTextBox, and passwordTextBox, and a 'sign in' button. 我创建了一个简单的Web表单,其中包含两个文本框:usernameTextBox和passwordTextBox,以及一个“登录”按钮。
For now, just for testing purposes, what I'm trying to do is to insert values into a users
table, when the sign in
button is clicked, so this is what I have so far: 就目前而言,仅出于测试目的,我想要做的是
sign in
单击“ sign in
按钮时将值插入到users
表中,因此,到目前为止,这就是我要做的:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _default : System.Web.UI.Page
{
protected void signInButton_Click(object sender, EventArgs e)
{
string connection_str="Data Source=.\\SQLEXPRESS;"+
"AttachDbFilename=|DataDirectory|\\project.mdf;"+
"Integrated Security=True;"+
"User Instance=True";
SqlConnection connection = new SqlConnection(connection_str);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText="INSERT INTO users VALUES ('"+userNameTextBox.Text+"','"+passwordTextBox.Text+"');";
command.ExecuteNonQuery();
connection.Close();
}
}
As stated above, this fails at connection.Open();
如上所述,这在
connection.Open();
处失败connection.Open();
. 。
The project.mdf
file is located at the VS Project folder, inside the 'App_Data' folder. project.mdf
文件位于“ App_Data”文件夹内的VS Project文件夹中。
Does anyone have an idea about what can cause the Open()
to fail? 有谁知道什么会导致
Open()
失败?
I can also provide the 'exception info', if it is needed. 如果需要,我还可以提供“例外信息”。
Thanks. 谢谢。
BTW, When should the connection be established? 顺便说一句,什么时候应该建立连接? at the 'sign-in-button handler', or in the 'Page_Load' handler?
在“登录按钮处理程序”中还是在“ Page_Load”处理程序中?
EDIT 编辑
System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060
Message=Cannot open user default database. Login failed.
Login failed for user 'J***-PC\J***'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=11
LineNumber=65536
Number=4064
Procedure=""
Server=\\.\pipe\8EDE82F8-E3AA-40\tsql\query
State=1
StackTrace:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at _default.signInButton_Click(Object sender, EventArgs e) in c:\Users\J***\Documents\Visual Studio 2012\Projects\db5774\default.aspx.cs:line 23
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
So the exception says: 因此,异常说明:
Message=Cannot open user default database.
Message =无法打开用户默认数据库。 Login failed.
登录失败。 Login failed for user 'J***-PC\\J***'.
用户“ J ***-PC \\ J ***”的登录失败。
That would mean the user has no access to the default database, usually master
. 这意味着用户无权访问默认数据库,通常是
master
。
Alter the user so it can access the default database, or better, point the default to another database. 更改用户,使其可以访问默认数据库,或者更好的是,将默认指向另一个数据库。
Use this sql for that: 为此使用此sql:
alter login [username] with default_database = database_that_user_can_access
Or change the connection string by adding this: 或通过添加以下内容来更改连接字符串:
Database=database_that_user_can_access
尝试这个:
AttachDbFilename=~\..\ProjectName\App_Data\project.mdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.