连接到另一台电脑的字符串

时间:2019-02-13 14:36:34

标签: c# asp.net visual-studio-2012

好吧,即时消息是数据库的新手,我仍在学习,因此我的sql本地数据库在我的PC上运行良好,无论何时我移动文件以在学院的PC或笔记本电脑上打开项目时,我都使用Visual Studio 2012数据库连接,因为该PC的连接字符串不同,因此我需要手动更改我的字符串,是否有简单的解决方案?需要帮助。

要使其正常工作,我必须每次手动对其进行字符串化

public partial class adminLogin : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\UsersSuren\Documents\Visual Studio 2012\Projects\Shopee mobile\Shopee mobile\App_Data\shopping.mdf;Integrated Security=True");
    int i;
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void b1_Click(object sender, EventArgs e)
    {
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandText = "select * from admin_login where username='"+t1.Text+"' and password='"+t2.Text+"'";
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        i = Convert.ToInt32(dt.Rows.Count.ToString());
        if (i == 1)
        {
            Response.Redirect("testing.aspx");
        }
        else
        {
            l1.Text = "Invalid password or username";
        }

        con.Close();
    }
}

3 个答案:

答案 0 :(得分:0)

在app.config上创建一个项目,例如

<add key="connectionString" value="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\UsersSuren\Documents\Visual Studio 2012\Projects\Shopee mobile\Shopee mobile\App_Data\shopping.mdf;Integrated Security=True"/>

,然后在您的adminLogin类上调用它,例如

SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["connectionString"].ToString());

现在,您可以在app.config中更改连接,而无需更改代码,也无需再次编译。

答案 1 :(得分:0)

使用元数据标签 | DataDirectory | 替换绝对路径,有关使用DataDirectory的更多信息,请参见here-位于底部。

您的情况应该是:

"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\shopping.mdf;Integrated Security=True"

我还建议将此类信息移至配置文件。

答案 2 :(得分:0)

您的问题有点令人困惑,但据我所知,您希望避免始终需要更改连接字符串路径,因为项目位于不同的位置,对吧?

您可以使用Directory.GetCurrentDirectory(),因为它获取了应用程序的当前工作目录,然后将其与您的连接字符串连接起来。

这将解决您始终必须手动将连接字符串更改为绝对路径的问题。

它看起来像这样:

SqlConnection con = new SqlConnection($@"Data Source=(LocalDB)\v11.0;AttachDbFilename={Directory.GetCurrentDirectory()}\Shopee mobile\App_Data\shopping.mdf;Integrated Security=True");