【问题标题】:Connection string to another pc到另一台电脑的连接字符串
【发布时间】:2019-02-13 14:36:34
【问题描述】:

好吧,我是数据库新手,我还在学习,所以我的 sql 本地数据库在我需要的电脑帮助上运行良好。

为了让它工作,我每次都必须手动串起来

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();

【问题讨论】:

  • 您的实际问题是什么?请在必要的部分更具体,而不是在开头详细:) 请查看“How to ask”以获得帮助
  • 欢迎来到 SO。 Karthik 大声笑,尝试查看@AlexK 的链接。张贴在他/她的评论中。它应该有助于回答您的问题,因为有一篇帖子获得了 80 多票。

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


【解决方案1】:

在 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 中更改连接,而无需更改代码且无需再次编译。

【讨论】:

    【解决方案2】:

    将绝对路径替换为元数据标记|DataDirectory|请参阅here,了解有关使用DataDirectory 的更多信息 - 它位于底部。

    在你的情况下应该是:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      看起来像这样:

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

      【讨论】:

        猜你喜欢
        • 2017-04-17
        • 2012-08-17
        • 2016-12-21
        • 1970-01-01
        • 1970-01-01
        • 2013-08-24
        • 2014-07-08
        • 1970-01-01
        • 2012-12-03
        相关资源
        最近更新 更多