Asp.net 如何从另一行值读取SQL数据库特定的行文本
我试图从另一列查询特定列文本的数据 基本上,我有一个供应商数据库,其中有一个SupplierID和Country列 我已经有了特定行的SupplierID,例如,它是14。我想根据14的值得到Country列的文本值 我通过以下代码获得的供应商ID(列表框):Asp.net 如何从另一行值读取SQL数据库特定的行文本,asp.net,sql,database,Asp.net,Sql,Database,我试图从另一列查询特定列文本的数据 基本上,我有一个供应商数据库,其中有一个SupplierID和Country列 我已经有了特定行的SupplierID,例如,它是14。我想根据14的值得到Country列的文本值 我通过以下代码获得的供应商ID(列表框): 现在还不清楚主要问题是什么,所以我将向您展示一个工作示例,该示例使用ADO.NET从数据库中选择Country列,使用参数避免SQL注入,并使用语句确保所有非托管资源作为连接被释放(关闭) 您需要研究如何使用参数化查询。试试这个:
现在还不清楚主要问题是什么,所以我将向您展示一个工作示例,该示例使用ADO.NET从数据库中选择
Country
列,使用参数避免SQL注入,并使用语句确保所有非托管资源作为连接被释放(关闭)
您需要研究如何使用参数化查询。试试这个:
string SupplierListvalue = SupplierListBox.SelectedItem.Value; //SupplierListvalue retrieves the SupplierID value
...
SqlCommand cmd = new SqlCommand("select Country from SupplierDB WHERE SupplierID = @supplierId", conn);
cmd.Parameters.AddWithValue("@supplierId", SupplierListvalue);
...
祝你好运。我走错了路。基本上,以下代码是正确的:
这就行了!现在,当我点击listbox1时,listbox2也会被点击,类似于级联 您是否尝试过从myTable中选择SupplierID=14的国家/地区?
?您尝试过查询数据吗?您正在使用什么rdbms,您希望如何查询它(ADO.NET、实体框架、Linq到Sql等等),最后,您已经尝试了什么?@TimSchmelter您的方法是正确的。我必须使用以下命令:SelectCommand=“从[SupplierDB]中选择[Company],[SupplierID],其中([SupplierID]=@SupplierID)”>//defaultvalue=“14”是数据库中的起始值SelectCommand=“从[SupplierDB]中选择[SupplierID],[Country],其中([SupplierID]=@SupplierID)”>
字符串SupplierListvalue=SupplierListBox.SelectedItem.Value;Show(SupplierListvalue.ToString());SqlConnection conn=newsqlconnection(“数据源=localhost;初始目录=ROG;集成安全=True”);SqlCommand cmd=new SqlCommand(“从[SupplierDB]中选择[Country],其中[SupplierID]=@SupplierID”,conn);cmd.Parameters.AddWithValue(“@SupplierID”,SupplierListvalue.ToString())代码>仍然无法基于Supplierlistvalue获取国家/地区文本。我有什么遗漏吗?
string SupplierListvalue = SupplierListBox.SelectedItem.Value; //SupplierListvalue retrieves the SupplierID value
SqlDataReader rdr = null;
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select Country from SupplierDB", conn);
cmd.Connection = conn;
conn.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
TextBox1.Text = rdr["Country"].ToString();
MessageBox.Show("Connection Successful");
MessageBox.Show(rdr.ToString());
}
conn.Close();
string sql = @"
SELECT Country
FROM dbo.Supplier
WHERE SupplierID = @SupplierId";
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
{
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
cmd.Parameters.Add("@SupplierId", SqlDbType.Int);
cmd.Parameters["@SupplierId"].Value = int.Parse(SupplierListBox.SelectedItem.Value);
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
TextBox1.Text = rdr.GetString(0);
}
}
}
}
string SupplierListvalue = SupplierListBox.SelectedItem.Value; //SupplierListvalue retrieves the SupplierID value
...
SqlCommand cmd = new SqlCommand("select Country from SupplierDB WHERE SupplierID = @supplierId", conn);
cmd.Parameters.AddWithValue("@supplierId", SupplierListvalue);
...