C#无法连接到本地SQL数据库
本文关键字:SQL 数据库 连接 | 更新日期: 2023-09-27 18:27:14
我已经创建了一个本地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服务器CE数据文件(.sdf
)。
如果要使用.sdf
,则需要使用SqlCeConnection
、SqlCeCommand
等。而不是SqlConnection
和SqlCommand