我創建了一個本地SQL Server數據庫和登錄形式,這裏是登錄窗體的代碼:C#無法連接到本地SQL數據庫
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 [email protected] and
[email protected]", 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 was unhandled
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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
你應該使用'using'塊。並且請不要將明文密碼放入數據庫。 – nvoigt 2014-10-19 15:49:28