我有一个字符串:
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/