C#Cant连接到本地SQL数据库

时间:2014-10-19 15:45:51

标签: c# database sql-server-ce

我已创建了本地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 - 查找指定的服务器/实例时出错)

2 个答案:

答案 0 :(得分:2)

要在ADO.NET中使用SQL Server Compact数据库文件,您需要使用System.Data.SqlServerCe.dll ADO.NET提供程序,并使用SqlCeConnection,SqlCeCommand等对象。

答案 1 :(得分:0)

您正在使用SqlConnection用于正确 SQL Server(基于服务器的系统),但您引用的是 SQL Server CE 数据文件(.sdf)。

如果您想使用.sdf,则需要使用SqlCeConnectionSqlCeCommand等 - SqlConnection和{{ 1}}