试图从我的应用程序建立连接时的SQL错误

发布于 2025-02-14 01:04:26 字数 5792 浏览 0 评论 0原文

我在C#中是全新的。我在将应用程序与SQL Server数据库联系起来时遇到了麻烦,当我单击检查或更新数据库的按钮时,就会发生问题。

我尝试了在Internet上发现的2种连接字符串方法,但它们都无法使用。现在也许我错误地理解了。我认为这可能是服务器代码的一部分或其他版本数据源我犯了一个错误,但不确定。基本上,我已经将VPS的IP地址放在那里(我在Nodejs中也将其连接到数据库)。

这些是我使用的2个连接字符串方法,它们不起作用:

const string connectionString = "SERVER = **.***.76.9; DATABASE = dbName; USER ID = root; PASSWORD =myPassword";

const string connectionString = "Data Source=**.**.76.9; Initial Catalog = dbName; User ID = root; Password=myPassword";

我还使用sqlconn.open();打开连接,这会导致错误,如我上面提到的。

system.data.sqlclient.sqlexception
hresult = 0x80131904

在建立与SQL Server的连接时,发生了与网络相关或实例特定的错误。该服务器未找到或无法访问。验证实例名称是正确的,并且配置了SQL Server以允许远程连接。 (提供商:命名Pipes提供商,错误:40-无法打开与SQL Server的连接)

source = .net sqlclient数据提供商
StackTrace:
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData ReconnectSessionData,dbConnectionpool池,字符串访问,布尔值applytransientfaulthandling,sqlauthentication providermanager sqlauthprovidermanager) at System.data.sqlclient.SQLConnectionFactory.CreateConnection(DBConnectionOptions选项,DBConnectionPoolkey PoolKey,Object PoolGrouOupProviderInfo,dbConnectionPool pool,dbConnectionpool pool,dbConnection andingConnection,dbConnectionOptions useroptions useroptions) at System.data.data.providerbase.dbConnectionFactory.CreatePooleDConnection(DBConnectionPool池,DBConnection onsingObject,dbConnectionOptions选项,DBConnectionPoolkey poolkey,dbConnectionPoolpool poolkey,dbConnectionOptions useroptions) 在System.Data.Data.ProviderBase.DBConnectionpool.CreateObject(dbConnection oningObject,dbConnectionOptions userOptions,dbConnection Interneal internal oldConnection) at System.data.providerbase.dbConnectionpool.usercreaterequest(dbConnection oningObject,dbConnectionOptions userOptions,dbConnection Internal ofternal old Conconnection) 在System.data.data.providerbase.dbconnectionpool.trygetConnection(dbConnection oningObject,uint32 waitgormultiplultipleObjectStimeout,boolean允许CREATEE,BOOLEAN OLLENECHECKCONNECTION,dBCONNectionOptions,dbConnectionOptions useroptions userOptions useroptions useroptions,dbConnectionNectioninectionInternal&Amp&Amp; Connection&Connection) 在System.Data.data.data.dbconnectionpool.trygetConnection(dbConnection andingObject,taskCompletionsourceource 1重试,DBConnectionOptions userOptions,dbConnectionInternal& amp; amp; amp; amp; amp; amp; amp; amp;连接) TaskCompletionsource 1重试,DBConnectionOptions,DBConnection Interther OldConnection,dbConnectioninternal& at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, dbConnectionFactory ConnectionFactory,TaskCompletionsource 1重试,dbConnectionOptions userOptions) at System.data.sqlClient.SQLConnection.Tryopeninner(taskCompletionsource 1重试)at System.data.data.sqlclient.sqlConnection.tryopen(taskCompletionsource 1 retry) 在system.data.sqlclient.sqlconnection.open() 在c:\ users \ users \ pc \ desktop \ myproject \ windowsclient \ myproject \ myproject \ forms \ activation.cs中,请访问myproject。 在c:\ users \ users \ pc \ desktop \ myproject \ windowsclient \ myproject \ myproject \ forms \ activation.cs:c:35 在c:\ users \ pc \ desktop \ myproject \ windowsclient \ myproject \ myproject \ forms \ form \ loginform.cs:line 100 100 在System.windows.forms.control.onclick(EventArgs e)上 在system.windows.forms.button.onclick(EventArgs e)上 在system.windows.forms.button.onmouseup(mouseeventargs mevent)上 在System.Windows.Forms.control.wmmouseup(消息& m,MouseButtons按钮,INT32点击) 在system.windows.forms.control.wndproc(消息& m) 在system.windows.forms.buttonbase.wndproc(消息& m)上 在system.windows.forms.button.wndproc(消息& m)上 at System.Windows.Forms.control.controlnativeWindow.onmessage(消息& m) 在system.windows.forms.control.controlnativewindow.wndproc(消息& m) 在System.Windows.Forms.nativeWindow.debuggableCallback(Intptr HWND,INT32 MSG,INTPTR WPARAM,INTPTR LPARAM)) 在system.windows.forms.unsafenativemethods.dispatchmessagew(msg& msg) at System.windows.forms.application.componentManager.system.windows.forms.unsafenativemethods.imsocomponentmanager.fpushmessageloop(intptr dwcomponentID,intptr dwcomponentId,int32,int32 pvloopdata) 在System.windows.forms.application.threadcontext.runmessageloopinner(int32原因,applicationContext上下文) 在System.Windows.Forms.Application.threadContext.runmessageloop(INT32原因,ApplicationContext Context) 在system.windows.forms.application.run(mainform) 在c:\ users \ pc \ desktop \ myproject \ windowsclient \ myproject \ myproject \ program.cs.cs:line 21

in myproject.program.main()

内部异常1:
Win32 Exception:找不到网络路径

这是我的代码:

    public static bool isActivated(string key)
    {
        using (SqlConnection sqlConn = new SqlConnection(connectionString))
        {
            string checkForActivationQuery = "SELECT activated FROM activationTable WHERE serialKey =@key";

            SqlCommand cmd = new SqlCommand(checkForActivationQuery, sqlConn);
            cmd.Parameters.AddWithValue("@key", key);

            sqlConn.Open();

            int result = Convert.ToInt32(cmd.ExecuteScalar());

            if (result > 0)
            {
                return true;
            }

            return false;
        }
    }

I'm totally new in C#. I'm having troubles with connecting my application with a SQL Server database, the problem occurs when I click the button which checks or updates my database.

I tried with 2 connection string methods I found on internet but neither of them work. Now maybe I understood it wrongly. I think it could be the SERVER part of code or the other version Data Source where I made a mistake but not quite sure. Basically I've put my VPS' IP address there (which I use in nodejs to connect to database as well).

Those are my 2 connection string methods I used which doesn't work:

const string connectionString = "SERVER = **.***.76.9; DATABASE = dbName; USER ID = root; PASSWORD =myPassword";

const string connectionString = "Data Source=**.**.76.9; Initial Catalog = dbName; User ID = root; Password=myPassword";

I'm also using sqlConn.Open(); to open connection which causes the error as I mentioned above.

System.Data.SqlClient.SqlException
HResult=0x80131904

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)

Source=.Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
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, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at myProject.Forms.activation.isActivated(String key) in C:\Users\PC\Desktop\myProject\WindowsClient\myProject\Forms\activation.cs:line 24
at myProject.Forms.activation.activateSoftware(String key) in C:\Users\PC\Desktop\myProject\WindowsClient\myProject\Forms\activation.cs:line 35
at myProject.Forms.LoginForm.button1_Click(Object sender, EventArgs e) in C:\Users\PC\Desktop\myProject\WindowsClient\myProject\Forms\LoginForm.cs:line 100
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at myProject.Program.Main() in C:\Users\PC\Desktop\myProject\WindowsClient\myProject\Program.cs:line 21

Inner Exception 1:
Win32Exception: The network path was not found

This is my code:

    public static bool isActivated(string key)
    {
        using (SqlConnection sqlConn = new SqlConnection(connectionString))
        {
            string checkForActivationQuery = "SELECT activated FROM activationTable WHERE serialKey =@key";

            SqlCommand cmd = new SqlCommand(checkForActivationQuery, sqlConn);
            cmd.Parameters.AddWithValue("@key", key);

            sqlConn.Open();

            int result = Convert.ToInt32(cmd.ExecuteScalar());

            if (result > 0)
            {
                return true;
            }

            return false;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淤浪 2025-02-21 01:04:27

您可以首先尝试另一种方式;使用

Data source =“serverName”;initial catalog=“dbname”; integrated security=true”

如果有效,则问题可能在您的凭据(用户名,密码)中。

You can first try the other way; use

Data source =“serverName”;initial catalog=“dbname”; integrated security=true”

If it works, then the problem is probably in your credentials (username, password).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文