c# - 字符串到 sqlsyntax

标签 c# asp.net mysql sql html

我有一个字符串:

string theUserId = Session["UserID"].ToString();

但我不知道如何将字符串添加到此 sqlsnytax

    {
        if (Session["UserID"] != null) 
        {
            string theUserId = Session["UserID"].ToString();
            Label1.Text = Convert.ToString(theUserId);


        OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite; User=x; Password=x;");
        cn.Open();
        OdbcCommand cmd = new OdbcCommand("SELECT User.FirstName, User.SecondName, User.Aboutme, User.DOB, Pictures.picturepath FROM User LEFT JOIN Pictures ON User.UserID = Pictures.UserID WHERE User.UserID=@UserID"), cn);

        cmd.Parameters.AddWithValue("@UserID", theUserId);

        OdbcDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            Name.Text = String.Format("{0} {1}", reader.GetString(0), reader.GetString(1));
            Aboutme.Text = String.Format("{0}", reader.GetString(2));
            Age.Text = String.Format("{0}", reader.GetString(3));
            Image1.ImageUrl = String.Format("{0}", reader.GetString(4));
        }


    }
}
}

User.UserID=1 我如何将其更改为类似 User.UserID="theUserId"

最佳答案

请参阅以下内容。要注意的第一件事是 USING 子句,它将清理您的连接。您要么使用这些,要么必须将所有内容包装在 try .. catches 中,并进行适当的处​​理调用。

if (Session["UserID"] != null) 
{
    string theUserId = Session["UserID"].ToString();
    Label1.Text = Convert.ToString(theUserId);

    using (OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite; User=root; Password=commando;")) {
        cn.Open();
        using (OdbcCommand cmd = new OdbcCommand("SELECT User.FirstName, User.SecondName, User.Aboutme, User.DOB, Pictures.picturepath FROM User LEFT JOIN Pictures ON User.UserID = Pictures.UserID WHERE User.UserID=@UserID", cn)) {

            cmd.Parameters.AddWithValue("@UserID", theUserId);

            using (OdbcDataReader reader = cmd.ExecuteReader()) {
                while (reader.Read())
                {
                    Name.Text = String.Format("{0} {1}", reader.GetString(0), reader.GetString(1));
                    Aboutme.Text = String.Format("{0}", reader.GetString(2));
                    Age.Text = String.Format("{0}", reader.GetString(3));
                    Image1.ImageUrl = String.Format("{0}", reader.GetString(4));
                }
            } // using reader
        } // using cmd
    } // using connection
}

关于c# - 字符串到 sqlsyntax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5382506/

相关文章:

c# - 在 C# 中尝试多线程

c# - 如何在 C# 中将 Excel 值转换为日期时间格式

PHP - mysql_fetch_array 如何给我选定的返回值?

c# - 如何报告 SharePoint 计时器作业的状态

C#,max,在列表中查找面积最大的矩形

c# - 通过存储到变量中来减少 SQL 查询?

c# - 回发后将焦点设置到任何控件

asp.net - 如何在 IIS 7 上托管 ASP.NET Web 应用程序站点

PHP 多个数据库连接失败

Python MySQL Spark(java.lang.ClassNotFoundException : com. mysql.jdbc.Driver)