0

您好,我在运行 SqlConnection 的类中有此代码:

using System.Data.SqlClient;
using System.IO;

namespace tours
{
    class myConnection
    {
        public static SqlConnection GetConnection()
        {
                string path = "C:\\Users\\marek\\Documents\\Visual Studio 2012\\Projects\\tours\\tours\\sql_string.txt";
                StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));

                string str = "Data Source='" + sr.ReadLine() + "';Initial Catalog ='" + sr.ReadLine() + "' ;User ='" + sr.ReadLine() + "';Password = '" + sr.ReadLine() + "'";

                SqlConnection spojeni = new SqlConnection(str);
                spojeni.Open();
                return spojeni;
        }
    }
}

在其他形式中,我得到SqlCommandSqlDataAdapter我需要添加到它们SqlConnection,但不知道如何访问它们?你能给我一些建议吗?例如这个:

DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM zajezd",);
SDA.Fill(dt);
4

2 回答 2

5

尝试

new SqlDataAdapter("SELECT * FROM zajezd",tours.myConnection.GetConnection())

或者您已经添加using tours;到文件顶部,然后您可以调用myConnection.GetConnection()

笔记:

将 myConnection 设为公开

public class myConnection

如果myConnection在单独的类库中,则需要添加对数据类库的引用


我会更改连接类仅返回连接字符串,如下所示

public class myConnection
{
    public static string GetConnectionString()
    {
        string connection = string.Empty;
        string path = "C:\\Users\\marek\\Documents\\Visual Studio 2012\\Projects\\tours\\tours\\sql_string.txt";
        using (StreamReader sr = new StreamReader(File.Open(path, FileMode.Open)))
        {
            connection = "Data Source='" + sr.ReadLine() + "';Initial Catalog ='" + sr.ReadLine() + "' ;User ='" + sr.ReadLine() + "';Password = '" + sr.ReadLine() + "'";

        } 

        return connection;

    }
}

当我们需要访问数据库时,

DataTable dt = new DataTable();

using (SqlConnection con = new SqlConnection(myConnection.GetConnectionString()))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM zajezd", con))
{
    adapter.Fill(dt);
}

如果您需要ExecuteNonQueryExecuteScalar

using (SqlConnection con = new SqlConnection(myConnection.GetConnectionString()))
using (SqlCommand commad = new SqlCommand("sql statements", con))
{
    con.Open();
    commad.ExecuteNonQuery(); 
    //var result = commad.ExecuteScalar();

}
于 2013-07-27T07:48:29.220 回答
0

您的方法名称是 GetConnection() 而不是 myConnection

于 2013-07-27T08:00:50.490 回答