SQL连接(异常失败)

时间:2016-05-17 11:36:20

标签: c# sql sql-server

当尝试通过sqlconnection连接到sql时出现错误," NullReferenceException未处理" "未处理的类型' System.NullReferenceException'发生在DBLabControllers.dll

其他信息:Objektreferensen har inte angetts直到en instans av ett objekt。"

为什么我会遇到异常失败以及如何解决?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;

namespace DBLabs
{


    public class DBConnection : DBLabsDLL.DBConnectionBase
    {


        public DBConnection()
        {
            string connectionString = null;
            SqlConnection connection;
            connectionString = "Data Source=(local);Initial Catalog=www3.idt.mdh.se;User ID=ezi15001;Password=********";

            connection = new SqlConnection(connectionString);
        }


        public override bool login(string username, string password)
        {


            string constring = "Data Source = www3.idt.mdh.se;" + "Database=" + username + "_db;" + "User ID=" + username + ";" + "Password=" + password;
            SqlConnection myConnection = new SqlConnection(constring);
            try
            {
                myConnection.Open();
            }
            catch (Exception)
            {
                myConnection.Close();
                return false;
            }
            finally
            {
                myConnection.Close();
            }
            return true;

        }
    }
}

1 个答案:

答案 0 :(得分:0)

在按钮单击方法中调用连接字符串之前,您将连接字符串设置为NULL,您需要将连接字符串传递给它。