An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dllОшибка: Необработанное исключение типа «System.Data.SqlClient.SqlException» произошло в System.Data.dll
Additional information: 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Я использовал эти коды:
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection();
public Form1()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sTUDENTDataSet.login' table. You can move, or remove it, as needed.
//this.loginTableAdapter.Fill(this.sTUDENTDataSet.login);
SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True");
con.Open();
{
}
}
private void btnLogin_Click_1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
con.Open();
string UserId = txtUsername.Text;
string UserPass = txtPassword.Text;
SqlCommand cmd = new SqlCommand("Select UserId,UserPass from Login where UserId='" + txtUsername.Text + "'and UserPass='" + txtPassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login sucess!");
Form2 form = new Form2();
form.Show();
}
else
{
MessageBox.Show("Invalid Login Information. Please check username and password");
}
con.Close();
}
Ошибка здесь является con.Open();
, которая принадлежит здесь :
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
con.Open();
Я попытался удалить его, потому что я не знаю, что еще сделать и второй ошибки на da.Fill(dt);
Так что я думаю, единственная проблема, которая должна быть действительно неподвижную является con.Open();
Что мне делать?
Если вы используете этот код в своем локальном хосте, попробуйте изменить источник данных на: localhost \ SQLEXPRESS, а также убедитесь, что имя каталога верное. –
Похоже, что БД находится на вашем локальном компьютере. Попробуйте подключиться к этому серверу базы данных, используя студию управления SQL-сервером и проверку подлинности Windows. Я чувствую, что имя хоста неверно. Если это правильно, проверьте, запущены и запущены все службы SQL Server. –
Также прочтите следующее: https://en.wikipedia.org/wiki/SQL_injection – n8wrl