我有一个字符串:
string theUserId = Session["UserID"].ToString();
但我不知道如何将字符串添加到此sql语法
{
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"
答案 0 :(得分:4)
请参阅以下内容。首先要注意的是USING子句,它将清理你的连接。你可以使用这些,或者你必须将所有内容包装在try ..中,并使用相应的处理调用进行捕获。
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
}
答案 1 :(得分:1)
string theUserId = Session[ "UserID" ].ToString();
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);
您可以使用@Parameter名称定义参数,然后使用.Parameters.AddWithValue
添加它们这比string.format更安全,或者自己整理字符串
答案 2 :(得分:0)
WHERE User.UserID = $UserID
然后将一个名为'$ UserID'的参数添加到您正在使用的Command对象中,它将在您执行查询时获取该值。
请注意,我不确定您使用的是什么驱动程序,我认为参数必须以$
为前缀,但我不是100%肯定。在SQL Server中,它是@
。
答案 3 :(得分:0)
你在找这样的东西吗?
string.Format(“SELECT User.FirstName,User.SecondName,User.Aboutme,User.DOB,Pictures.picturepath FROM User LEFT JOIN Pictures ON User.UserID = Pictures.UserID WHERE User.UserID = {0}” ,theUserId);