来自文本文件的C#SQL Server类连接字符串[错误实例失败]

时间:2017-01-24 02:28:27

标签: c# sql-server

我将连接字符串保存在文本文件中,如下所示:

koneksi.txt

Data Source=GGL-TBGIT-PC02\\SQLEXPRESS; Initial Catalog=db_timbangan;user=sa;password=GGL654321

这是我的班级连接

class Koneksi
{
    public System.Data.SqlClient.SqlConnection GetConn()
    {
        string path;
        TextReader tr = new StreamReader(@"D:\PROJECT\2.0 TIMBANGAN\TIMBANGAN\koneksi.txt");
        path = tr.ReadLine();
        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();            
        conn.ConnectionString = path;
        return conn;
    }
}

这是我的登录

Koneksi konn = new Koneksi();
    public Login()
    {
        InitializeComponent();
        this.AcceptButton = button1;
    }

    private Boolean statusLogin(string username, string password)
    {
        System.Data.SqlClient.SqlConnection conn = konn.GetConn();
        conn.Open();
        string sql = "select * from tbl_login where username='" + username + "' AND password='" + password + "'";
        SqlCommand command = new SqlCommand(sql, conn);
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            if (reader["username"].ToString() == username && reader["password"].ToString() == password)
            {

                return true;
            }
        }
        conn.Close();
        return false;
    }

当我尝试登录时, conn.Open()的错误实例失败

如何解决?

1 个答案:

答案 0 :(得分:0)

尝试仅使用一个\

的连接字符串

Data Source=GGL-TBGIT-PC02\SQLEXPRESS; Initial Catalog=db_timbangan;user=sa;password=GGL654321

此外,您应该使用using进行SQL连接。

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    //read here
    connection.Close();
}