【问题标题】:C# Cant connect to Local SQL databaseC# 无法连接到本地 SQL 数据库
【发布时间】:2014-10-19 15:45:51
【问题描述】:

我已经创建了一个本地 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 - 错误定位服务器/指定的实例)

【问题讨论】:

  • 您应该使用using 块。并且请不要将明文密码放入您的数据库中。

标签: c# database sql-server-ce


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    如果你想使用.sdf,你需要使用SqlCeConnectionSqlCeCommand等等-不是SqlConnectionSqlCommand

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多