SqlConnection.Open抛出异常C#

时间:2017-02-13 12:51:02

标签: c# visual-studio

尝试在C#中创建登录表单,并连接到SQL server。但它不断在cn.Open();抛出异常。我在XAMPP使用SQL Server

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;

namespace BlackLight_CSharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cn = new SqlConnection("server=localhost;user id=root;database=blacklight_login");
            cn.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM login WHERE Username= '"+txt_user.Text+"' AND Password = '"+txt_pass.Text+"'", cn);
            SqlDataReader dr;
            dr = cmd.ExecuteReader();
            int count = 0;
            while (dr.Read())
            {
                count += 1;
            }

            if (count == 1)
            {
                MessageBox.Show("OK");
                dashboard dash = new dashboard();
                dash.Show();
            }
            else if (count > 0)
            {
                MessageBox.Show("Duplicate Username and Password");
            }
            else
            {
                MessageBox.Show("Incorrect Username or Password, Try again.");
            }

            txt_user.Clear();
            txt_pass.Clear();
        }
    }
}

以下是错误的屏幕截图

Error 1

Error 2

2 个答案:

答案 0 :(得分:1)

对于您需要的MySql服务器 MySql.Data.MySqlClient.MySqlConnection而不是SqlConnection。 检查:https://www.codeproject.com/Articles/43438/Connect-C-to-MySQL

答案 1 :(得分:1)

明确表示您正在使用MySQL并且您正在使用SqlClient支持MSSQL将数据库数据提供者更改为MySQL并使用MySql.Data.MySqlClient.MySqlConnection代替exec.Command("netsh", "interface", "ipv6", "set", "privacy", "state=disable").Run()