簡體   English   中英

C#無法連接到本地SQL數據庫

[英]C# Cant connect to Local SQL database

我已經創建了本地SQL Server數據庫和“登錄”表單,這是“登錄”表單的代碼:

namespace WindowsFormsApplication1
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!(Usertxt.Text == string.Empty))
            {
                    SqlConnection connection = new SqlConnection(@"Data Source=|DataDirectory|\crimemanagement.sdf");
                    connection.Open();

                    SqlCommand cmd = new SqlCommand(@"SELECT Count(*) FROM Login_table 
                                        WHERE Username=@Username and 
                                        Password=@Password", connection);

                    cmd.Parameters.AddWithValue("@Username", Usertxt.Text);
                    cmd.Parameters.AddWithValue("@Password", Passtxt.Text);

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

                    if (result > 0)
                    {
                        MessageBox.Show("Login Success");
                    }
                    else
                    {
                        MessageBox.Show("Incorrect login");
                    }
            }
            else if (Passtxt.Text == string.Empty || Usertxt.Text == string.Empty)
            {
                MessageBox.Show("Enter Username and Password");
            }
        }
    }
}

但是,當我嘗試使用創建的表單登錄時,出現連接錯誤並突出顯示connection.open();

未處理System.Data.SqlClient.SqlException

建立與SQL Server的連接時,發生了與網絡相關或特定於實例的錯誤。 服務器未找到或無法訪問。 驗證實例名稱正確,並且已將SQL Server配置為允許遠程連接。 (提供者:SQL網絡接口,錯誤:26-指定服務器/實例時出錯)

為了在ADO.NET中使用SQL Server Compact數據庫文件,您需要使用System.Data.SqlServerCe.dll ADO.NET提供程序,並使用SqlCeConnection,SqlCeCommand等對象。

您正在使用適用於適當的 SQL Server( 基於服務器的系統)的SqlConnection ,但是您引用的是SQL Server CE數據文件( .sdf )。

如果要使用.sdf ,則需要使用SqlCeConnectionSqlCeCommand等- 而不是 SqlConnectionSqlCommand

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM